MCPcopy Create free account
hub / github.com/Apress/modern-pyqt / setupChart

Method setupChart

ch03_data_visualization/data_visualization.py:67–146  ·  view source on GitHub ↗

Set up the GUI's graph series type, chart instance, chart axes, and chart view widget.

(self)

Source from the content-addressed store, hash-verified

65 self.show()
66
67 def setupChart(self):
68 """Set up the GUI's graph series type, chart instance, chart axes,
69 and chart view widget."""
70 random.seed(50) # Create seed for random numbers
71
72 # Create the model instance and set the headers
73 self.model = QStandardItemModel()
74 self.model.setColumnCount(3)
75 self.model.setHorizontalHeaderLabels(["Year", "Social Exp. %GDP", "Country"])
76
77 # Collect x and y data values and labels from the CSV file
78 xy_data_and_labels = self.loadCSVFile()
79
80 # Create the individual lists for x, y and labels values
81 x_values, y_values, labels = [], [], []
82 # Append items to the corresponding lists
83 for item in range(len(xy_data_and_labels)):
84 x_values.append(xy_data_and_labels[item][0])
85 y_values.append(xy_data_and_labels[item][1])
86 labels.append(xy_data_and_labels[item][2])
87
88 # Remove all duplicates from the labels list using list comprehension.
89 # This list will be used to create the labels in the chart's legend.
90 set_of_labels = []
91 [set_of_labels.append(x) for x in labels if x not in set_of_labels]
92
93 # Create chart object
94 self.chart = QChart()
95 self.chart.setTitle("Public Social Spending as a Share of GDP, 1880 to 2016")
96 self.chart.legend().hide() # Hide legend at the start
97
98 # Specify parameters for the x and y axes
99 self.axis_x = QValueAxis()
100 self.axis_x.setLabelFormat("%i")
101 self.axis_x.setTickCount(10)
102 self.axis_x.setRange(1880, 2016)
103 self.chart.addAxis(self.axis_x, Qt.AlignBottom)
104
105 self.axis_y = QValueAxis()
106 self.axis_y.setLabelFormat("%i" + "%")
107 self.axis_y.setRange(0, 40)
108 self.chart.addAxis(self.axis_y, Qt.AlignLeft)
109
110 # Create a Python dict to associate the labels with the individual line series
111 series_dict = {}
112
113 for label in set_of_labels:
114 # Create labels from data and add them to a Python dictionary
115 series_label = 'series_{}'.format(label)
116 series_dict[series_label] = label # Create label value for each line series
117
118 # For each of the keys in the dict, create a line series
119 for keys in series_dict.keys():
120 # Use get() to access the corresponding value for a key
121 label = series_dict.get(keys)
122
123 # Create line series instance and set its name and color values
124 line_series = QLineSeries()

Callers 2

initializeUIMethod · 0.95
changeChartThemeMethod · 0.95

Calls 2

loadCSVFileMethod · 0.95
ChartViewClass · 0.85

Tested by

no test coverage detected