def create_donutchart(self, chartKey): series = QPieSeries() series.setHoleSize(0.35) for key, value in sample[chartKey].items(): series.append(key, value) slice = QPieSlice() chart = QChart() #chart.legend().hide() chart.addSeries(series) # for the background and title chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("DonutChart Example") chart.setTheme(QChart.ChartThemeBlueCerulean) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) # creating a widget object widget = QWidget() # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) self.setCentralWidget(chartview) series.doubleClicked.connect(self.handle_double_clicked)
def process(self): ''' Processes Summary and Chart Data ''' self.summary = { 'AtkCount': self.data.loc['IsAtk'].value_counts() [1], # count number of 1s in the column 'IP': self.data.loc['IP'].value_counts().to_dict(), 'Protocol': self.data.loc['Protocol'].value_counts().to_dict(), 'Port': self.data.loc['Port'].value_counts(), 'Atk': self.data.loc['Atk'].value_counts(), } # process piechart data series = QPieSeries() for atk, val in self.summary['Atk'].items(): series.append(str(atk), int(val)) self.series = series # process top protocol data self.protoports = self.data.transpose().groupby(["Protocol", "Port" ]).size().to_dict() self.protoports = { str(key[0]) + ':' + str(key[1]): value for key, value in self.protoports.items() } # create dictionary with key of format "protocol:port" # process barchart data self.bardata = self.data.transpose() self.bardata = pd.to_datetime(self.bardata['Time'], unit='s') self.bardata = self.bardata.groupby( [self.bardata.dt.year, self.bardata.dt.month])
class Chart(QWidget): def __init__(self, chartKey, data, frame, parent=None): super(Chart, self).__init__(parent) self.frame = frame self.data = data self.create_chart(chartKey) def create_chart(self, chartKey): self.series = QPieSeries() self.series.setHoleSize(0.35) self.chart = QChart() #Add series to the chart self.addSeries(chartKey) # for the background and title self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setTitle("Code Size Visualizer") self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignRight) self.chart.setTheme(QChart.ChartThemeBlueCerulean) self.chartview = QChartView(self.chart) self.chartview.setRenderHint(QPainter.Antialiasing) #each section of the pie chart def addSeries(self, key): self.chart.removeAllSeries() self.series = QPieSeries() self.series.setHoleSize(0.35) #Show chartview only if the content length is less than 6. Otherwise show a table view if len(self.data[key]) < 6: #print('length',self.data, key) for key, value in self.data[key].items(): print('key, value', key, value) slice_ = QPieSlice(str(key), value) self.series.append(slice_) self.series.setLabelsVisible() self.series.setLabelsPosition(QPieSlice.LabelInsideHorizontal) for slice in self.series.slices(): #slice.setLabel(slice.label()) slice.setLabel(slice.label() + ' - ' + str(slice.value()) + ' B ') self.chart.addSeries(self.series) self.frame.frame.hide() self.chart.show() else: self.table = TableView(self.data[key], len(self.data[key]), 1) if self.frame.ly.count() > 0: self.frame.ly.itemAt(0).widget().setParent(None) self.frame.ly.addWidget(self.table) self.frame.frame.show() self.chart.hide()
def __init__(self): super(MainWindow, self).__init__() ''' Load the UI file from disk (UI file was created in QT Designer) ''' uic.loadUi("mainwindow.ui", self) ''' Create an instance of the database class ''' self.dbase = db.database( ) # Create an instance of the database as self.dbase '''call the Connect method on our new database object (Creates a database connection) ''' self.dbase.Connect() self.conn = self.dbase.getConn() ''' Set up the menubar ''' self.createMenus() self.carsModel = cars.carsModel() setupUI.doSetup(self) self.dbase.populateView(self, "select * from car order by make asc", self.carsModel) mySeries = QPieSeries() mySeries.append("jane", 2) mySeries.append("joe", 8) chart = QChart() chart.addSeries(mySeries) chart.setTitle("Simple piechart example") chart.legend().hide()
def create_predict_pieseries(self, bots_part): human_part = 1 - bots_part percentage_bots_part = int(round(bots_part * 100)) percentage_human_part = 100 - percentage_bots_part # define the series slices of the pie series = QPieSeries() bot_slice = QPieSlice(f"Bot ({percentage_bots_part}%)", bots_part) human_slice = QPieSlice(f"Human ({percentage_human_part}%)", human_part) font = QFont() font.setBold(True) bot_slice.setColor(QColor("#3498db")) bot_slice.setLabelFont(font) human_slice.setColor(QColor("#a8e6cf")) human_slice.setLabelFont(font) series.append(bot_slice) series.append(human_slice) series.setLabelsVisible(False) series.setLabelsPosition(QPieSlice.LabelInsideHorizontal) series.setPieSize(0.94) return series
def analyseProcess(self): absc = [] ordo = [] absc.clear() ordo.clear() for tabrow in range(self.tableWidget.rowCount()): abscitem = self.tableWidget.item(tabrow, self.comboBoxabsc.currentIndex()) ordoitem = self.tableWidget.item(tabrow, self.comboBoxordo.currentIndex()) absc.append(int(abscitem.text())) ordo.append(str(ordoitem.text())) df = pd.DataFrame({'data': absc}) df.index = ordo df = df.sort_values(by='data', ascending=False) df["cumpercentage"] = df["data"].cumsum() / df["data"].sum() * 100 self.figure.clear() plt.ion() ax = self.figure.add_subplot() ax.bar(df.index, df["data"], color="C0") ax2 = ax.twinx() ax2.plot(df.index, df["cumpercentage"], color="C1", marker="D", ms=7) ax2.yaxis.set_major_formatter(PercentFormatter()) ax.tick_params(axis="y", colors="C0") ax2.tick_params(axis="y", colors="C1") self.canvas.draw() # donutchart*********************************** self.m_donuts = [] self.chartView3.setRenderHint(QPainter.Antialiasing) self.chart3 = self.chartView3.chart() self.chart3.legend().setVisible(True) self.chart3.setTitle("Nested donuts Chart") self.chart3.setAnimationOptions(QChart.AllAnimations) minSize3 = 0.1 maxSize3 = 0.9 donutCount3 = 5 for i in range(donutCount3): donut = QPieSeries() sliceCount = random.randrange(3, 6) # print(sliceCount) for j in range(sliceCount): value3 = random.randrange(0, 50) slice_ = QPieSlice(str(value3), value3) slice_.setLabelVisible(True) slice_.setLabelColor(Qt.white) slice_.setLabelPosition(QPieSlice.LabelInsideTangential) slice_.hovered[bool].connect( functools.partial(self.explodeSlice, slice_=slice_)) donut.append(slice_) donut.setHoleSize(minSize3 + i * (maxSize3 - minSize3) / donutCount3) donut.setPieSize(minSize3 + (i + 1) * (maxSize3 - minSize3) / donutCount3) self.m_donuts.append(donut) self.chartView3.chart().addSeries(donut) self.updateTimer = QTimer(self) self.updateTimer.timeout.connect(self.updateRotation) self.updateTimer.start(1250) self.tabWidget.setCurrentIndex(2)
def load_slices(self): series = QPieSeries() for i in EXTENSHIONS.keys(): slice = QPieSlice(i, EXTENSHIONS[i][0]) v = EXTENSHIONS[i][1] slice.setPen(QPen(Qt.black, 2)) slice.hovered[bool].connect(functools.partial(self.explodeSlice, slice_=slice, v=v)) series.append(slice) return series
def get_data(self, mark_data): pie_series = QPieSeries() # 定义PieSeries total_area = 0 for j in range(len(mark_data)): total_area += mark_data[j][1] for j in range(len(mark_data)): percentage = mark_data[j][1] / total_area * 100 str1 = "{:.1f}%".format(percentage) + mark_data[j][0] pie_series.append(str1, mark_data[j][1]) return pie_series
def graph_chart(self): series = QPieSeries() for i in range(self.table.rowCount()): text = self.table.item(i, 0).text() val = float(self.table.item(i, 1).text().replace('$', '')) series.append(text, val) chart = QChart() chart.addSeries(series) chart.legend().setAlignment(Qt.AlignTop) self.chartView.setChart(chart)
def createChart(self, names, values, title): series = QPieSeries() for name, value in zip(names, values): series.append(name + " " + str(value) + "%", value) chart = QChart() chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle(title) chart.legend().setVisible(True) return chart
def getSeries(self): series = QPieSeries() slice0 = series.append('10%', 1) series.append('20%', 2) series.append('70%', 7) # 显示label文字 series.setLabelsVisible() series.setPieSize(0.5) # 使第一块突出显示 slice0.setLabelVisible() slice0.setExploded() # 设置第一块颜色 slice0.setColor(QColor(255, 0, 0, 100)) return series
def createSummaryBar(self): # self.dp.dfinal series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) linked_bag, unlinked_bag = 0, 0 try: linked_bag = len(self.linked.index) unlinked_bag = len(self.unlinked.index) # slices.setPen(QPen(Qt.darkGreen, 2)) # slices.setBrush(QBrush(QColor(0xfdb157))) except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Linked", linked_bag) series.append("Unlinked", unlinked_bag) slices = series.slices()[0] slices.setBrush(QBrush(QColor(0x57B1FD))) slices.setLabelVisible() slices.setLabel(("{0} {1:.2f}%").format("Linked", 100*slices.percentage())) slices.setLabelFont(labelfont) slices1 = series.slices()[1] slices1.setExploded() slices1.setLabelVisible() slices1.setPen(QPen(QColor(0x57B1FD), 2)) slices1.setBrush(QBrush(QColor(0xfdb157))) # slices1.setLabelPosition(QPieSlice.LabelOutside) slices1.setLabel(("{0} {1:.2f}%").format("Unlinked", 100*slices1.percentage())) slices1.setLabelFont(labelfont) # slices.setLabel(("%1%").format(100*slices.percentage(), 0, 'f', 1)) # slices.setLabelPosition(QPieSlice.LabelInsideHorizontal) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def create_initialize_pieseries(self): color = QColor("#757a79") # define the series slices of the pie series = QPieSeries() none_slice = QPieSlice("Undefined", 1.0) none_slice.setColor(color) none_slice.setBorderColor(color) series.append(none_slice) series.setLabelsVisible(False) series.setLabelsPosition(QPieSlice.LabelOutside) series.setPieSize(0.94) return series
def make_cake( self ): score_1 = self.players[ 0 ].score score_2 = self.players[ 1 ].score series = QPieSeries() free_score = 120 - score_1 - score_2 series.append( f"{free_score}", free_score ) series.append( f"{score_1}", score_1 ) series.append( f"{score_2}", score_2 ) series.setPieStartAngle( 3 * score_2 ) series.setPieEndAngle( 3 * score_2 + 360 ) slices = series.slices() for slice in slices: slice.setLabelVisible( True ) if slice.angleSpan() < 45: slice.setLabelPosition( QPieSlice.LabelPosition.LabelInsideNormal ) elif slice.angleSpan() < 90: slice.setLabelPosition( QPieSlice.LabelPosition.LabelInsideTangential ) else: slice.setLabelPosition( QPieSlice.LabelPosition.LabelInsideHorizontal ) slice.setLabelColor( QColor( "#00000" ) ) slice.setLabelFont( QFont( "Fira Sans", 60, weight=QFont.Weight.Black ) ) slice.setBorderWidth( 0 ) slices[ 0 ].setLabelPosition( QPieSlice.LabelPosition.LabelInsideHorizontal ) if score_1 < 10: slices[ 1 ].setLabelFont( QFont( "Fira Sans", score_1 * 6, weight=QFont.Weight.Black ) ) if score_2 < 10: slices[ 2 ].setLabelFont( QFont( "Fira Sans", score_2 * 6, weight=QFont.Weight.Black ) ) slices[ 0 ].setLabelColor( QColor( "#FFFFFF" ) ) slices[ 0 ].setColor( remaining_points_color ) slices[ 1 ].setColor( player_1.color ) slices[ 2 ].setColor( player_2.color ) chart = QChart() chart.legend().hide() chart.addSeries( series ) chart.createDefaultAxes() chart.setBackgroundVisible( False ) chart.setContentsMargins( -120, -120, -120, -120 ) chart.layout().setContentsMargins( 0, 0, 0, 0 ) chart_view = QChartView( chart ) chart_view.setRenderHint( QPainter.Antialiasing ) return chart_view
def create_piechart(self): today = datetime.date.today() Day = selectday(today) catogeries = Day['allCategory'] catogeries = dict(sorted(catogeries.items(), key=lambda x: -x[1])[:5]) print(f"--------------------{catogeries}--------") series = QPieSeries() tot_val = 0 for name, value in catogeries.items(): tot_val += value tot_val = max(tot_val, 1) for name, value in catogeries.items(): if value == 0: value = 0.2 _slice = series.append(name, 100 * (value / tot_val)) _slice.setLabelVisible(True) # can be removed if unnecessary self.chart = QChart() self.chart.legend().hide() self.chart.addSeries(series) self.chart.createDefaultAxes() self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setTitle("Categories") self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom) self.chartview = QChartView(self.chart) self.chartview.setRenderHint(QPainter.Antialiasing)
def on_collect_finished(self): # 输出后缀统计扇形图 suffix_list = self.resopt.get_suffix_list(5) all = self.resopt.count_all() self.chart.removeAllSeries() series = QPieSeries() for (suffix, count) in suffix_list: series.append(suffix, count) all -= count if all > 0: series.append('others', all) series.setLabelsVisible(True) self.chart.addSeries(series) # 设置按键和进度条 self.collectPushButton.setEnabled(True) self.progressBar.hide()
class Chart(QWidget): def __init__(self, chartKey, parent=None): super(Chart, self).__init__(parent) self.create_chart(chartKey) def create_chart(self, chartKey): self.series = QPieSeries() self.series.setHoleSize(0.35) self.chart = QChart() #Add series to the chart self.addSeries(chartKey) # for the background and title self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setTitle("DonutChart Example") self.chart.setTheme(QChart.ChartThemeBlueCerulean) self.chartview = QChartView(self.chart) self.chartview.setRenderHint(QPainter.Antialiasing) def addSeries(self, key): self.chart.removeAllSeries() self.series = QPieSeries() self.series.setHoleSize(0.35) for key, value in sampleData[key].items(): print("adding series", str(key), value) slice_ = QPieSlice(str(key), value) self.series.append(slice_) self.chart.addSeries(self.series) self.series.doubleClicked.connect(self.handle_double_clicked) #Show the update chart with the distribution of the selected slice def handle_double_clicked(self, slice): slice.setExploded() slice.setLabelVisible() if slice.label() in sampleData.keys(): print("slice",slice.label()); self.addSeries(slice.label())
def afterDelayPieChart(self): series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) total_running_after_delay, total_stopped_after_delay = [], [] try: total_running_after_delay = self.tm.total_running_after_delay total_stopped_after_delay = self.tm.total_stopped_after_delay # slices.setPen(QPen(Qt.darkGreen, 2)) # slices.setBrush(QBrush(QColor(0xfdb157))) except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Run", sum(total_running_after_delay)) series.append("Stop", sum(total_stopped_after_delay)) # slices = QPieSlice() slices = series.slices()[0] # Run time slice slices.setBrush(QBrush(QColor(0x57B1FD))) # Blue slices.setLabelVisible() # Set label visible slices.setLabel(("{0} {1:.2f}%").format("Run time", 100*slices.percentage())) # Set percentage slices.setLabelFont(labelfont) # Set label font slices1 = series.slices()[1] # Stop time slice slices1.setExploded() # Set stop slice exploded slices1.setLabelVisible() # Set label visible slices1.setPen(QPen(QColor(0x57B1FD), 2)) # Blue slices1.setBrush(QBrush(QColor(0xA6E22E))) # Orange # slices1.setLabelPosition(QPieSlice.LabelOutside) # Set label outside slices1.setLabel(("{0} {1:.2f}%").format("Stop time", 100*slices1.percentage())) # Set percentage slices1.setLabelFont(labelfont) # Set label font chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total Time (after)") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def update_diagram(self): year = self.date_edit.get_year() month = self.date_edit.get_month() date_format = f"WHERE strftime(\"%Y\",DATE) = \"{year}\" AND strftime(\"%m\",DATE) = \"{month:02}\"" series = QPieSeries() for item in self.db.get_sum_by_category(date_format, self.type_inout): series.append(item[1], item[0]) for slice in series.slices(): slice.setLabel( slice.label() + ", " + f"{slice.value()}₽" + f" ({round(slice.value() / (series.sum() / 100))}%)") series.clicked.connect(self.pressed) self.chart.removeAllSeries() self.chart.addSeries(series) self.chart.setTitle("Доходы" if self.type_inout else "Расходы")
def beforeDelayPieChart(self): series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) total_running_time, total_stopped_time = [], [] try: total_running_time = self.tm.total_running_time total_stopped_time = self.tm.total_stopped_time # slices.setPen(QPen(Qt.darkGreen, 2)) # slices.setBrush(QBrush(QColor(0xfdb157))) except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Run", sum(total_running_time)) series.append("Stop", sum(total_stopped_time)) slices = series.slices()[0] slices.setBrush(QBrush(QColor(0x57B1FD))) slices.setLabelVisible() slices.setLabel(("{0} {1:.2f}%").format("Run Time", 100*slices.percentage())) slices.setLabelFont(labelfont) slices1 = series.slices()[1] slices1.setExploded() slices1.setLabelVisible() slices1.setPen(QPen(QColor(0x57B1FD), 2)) slices1.setBrush(QBrush(QColor(0xfdb157))) slices1.setLabel(("{0} {1:.2f}%").format("Stop Time", 100*slices1.percentage())) slices1.setLabelFont(labelfont) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total Time (before)") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def createSummaryBar(self): series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) linked_bag, unlinked_bag = 0, 0 try: linked_bag = self.scanner_linked_rfid unlinked_bag = self.total_bins - linked_bag except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Linked", linked_bag) series.append("Unlinked", unlinked_bag) slices = series.slices()[0] slices.setBrush(QBrush(QColor(0x57B1FD))) slices.setLabelVisible() slices.setLabel(("{0} {1:.2f}%").format("Linked", 100*slices.percentage())) slices.setLabelFont(labelfont) slices1 = series.slices()[1] slices1.setExploded() slices1.setLabelVisible() slices1.setPen(QPen(QColor(0x57B1FD), 2)) slices1.setBrush(QBrush(QColor(0xfdb157))) slices1.setLabel(("{0} {1:.2f}%").format("Unlinked", 100*slices1.percentage())) slices1.setLabelFont(labelfont) chart = QChart() chart.setTheme(QChart.ChartThemeHighContrast) font = QFont() font.setPixelSize(16) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def create_piechart(self, names, appendList, rg, title): self.w = Window2() self.w.show() series = QPieSeries() print(names, appendList) for x in range(rg): series.append(names[x], appendList[x]) chart = QChart() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle(title) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) self.w.setCentralWidget(chartview)
def get_pie_series(self): """ TODO:订单管理界面点击统计调用该函数,计算订单管理界面当前搜索范围内所有订单 各大类 书的销售额 按以下格式放入 series.append('类别x%', 销售额) """ totals, classes = self.database.stat_2(*self.data) all_total = sum(totals) if all_total: series = QPieSeries() for i in range(len(totals)): if totals[i]: word = (classes[i] + ' %.2f' % (totals[i])) series.append(word, totals[i]) else: series = QPieSeries() series.append('无销售', 1) series.setLabelsVisible() series.setPieSize(0.7) return series
def updateChart(self): country = str(self.m_countryComboBox.currentText()) response = request(country) cases = float(response[0].strip().replace(",", "")) deaths = float(response[1].strip().replace(",", "")) recovered =float(response[2].strip().replace(",", "")) data_list = [("Cases:" + response[0], cases), ("Deaths:" + response[1], deaths), ("Recovered:" + response[2], recovered)] self.m_chartView.chart().removeAllSeries() series = QPieSeries(self.m_chartView.chart()) for tag, valor in data_list: series.append(tag, valor) self.m_chartView.chart().setTitle(country + " Corona Status") self.m_chartView.chart().addSeries(series) self.updateUI()
def createGraphicCircular(self): response = request("World") graphic = QChart() graphic.setTitle("World Corona Status") cases = float(response[0].strip().replace(",", "")) deaths = float(response[1].strip().replace(",", "")) recovered = float(response[2].strip().replace(",", "")) data_list = [("Cases:" + response[0], cases), ("Deaths:" + response[1], deaths), ("Recovered:" + response[2], recovered)] series = QPieSeries(graphic) for tag, valor in data_list: series.append(tag, valor) graphic.addSeries(series) graphic.createDefaultAxes() return graphic
def drawChart(self, mui): series = QPieSeries() series.append("Main", mui.keyfunc.mainActivityFrame) series.append("Key", mui.keyfunc.keyActivityFrame) slice1 = series.slices()[0] #slice1.setExploded() slice1.setLabelVisible() slice1.setPen(QPen(QColor(40, 100, 240, 250), 2)) slice1.setBrush(QColor(40, 100, 240, 200)) slice2 = series.slices()[1] slice2.setLabelVisible() slice2.setPen(QPen(QColor(20, 150, 240, 250), 2)) slice2.setBrush(QColor(20, 150, 240, 200)) chart = QChart() chart.addSeries(series) #chart.setTitle("Activity Details") #chart.legend().hide() self.chartView.setChart(chart)
def create_pie(self, data): series = QPieSeries() self.build_pie(data) if self.quantita_categoria == []: QMessageBox.critical(self, 'Errore', 'Nessuna statistica da visualizzare', QMessageBox.Ok, QMessageBox.Ok) else: try: slice = series.append(self.categoria[0], self.quantita_categoria[0]) slice.setBrush(QtGui.QColor("#FF5631")) slice = series.append(self.categoria[1], self.quantita_categoria[1]) slice.setBrush(QtGui.QColor("#31B1FF")) slice = series.append(self.categoria[2], self.quantita_categoria[2]) slice.setBrush(QtGui.QColor("#31FF4D")) slice = series.append(self.categoria[3], self.quantita_categoria[3]) slice.setBrush(QtGui.QColor("#DA31FF")) slice = series.append(self.categoria[4], self.quantita_categoria[4]) slice.setBrush(QtGui.QColor("#FFEC31")) except IndexError: pass chart = QChart() font = QFont() font.setPointSize(18) chart.addSeries(series) chart.setTitleFont(font) chart.setTitle(self.set_title(data)) self.chartview = QChartView(chart)
def create_chart(self): self.chart.setTitle( 'Grafiek aantal externe werken per status - opnameweek ' + jrwk) font = QFont("Sans Serif", 10) font.setWeight(QFont.Bold) self.chart.setTitleFont(font) series = QPieSeries() slice_ = QPieSlice() series.setUseOpenGL(enable=True) series.append('Status A = ' + str(rpr[0][2]), rpr[0][2]) series.append('Status B = ' + str(rpr[1][2]), rpr[1][2]) series.append('Status C = ' + str(rpr[2][2]), rpr[2][2]) series.append('Status D = ' + str(rpr[3][2]), rpr[3][2]) series.append('Status E = ' + str(rpr[4][2]), rpr[4][2]) series.append('Status F = ' + str(rpr[5][2]), rpr[5][2]) series.append('Status G = ' + str(rpr[6][2]), rpr[6][2]) series.append('Status H = ' + str(rpr[7][2]), rpr[7][2]) for i, slice_ in enumerate(series.slices()): slice_.setLabelVisible() #slice_.setLabelPosition(3) if i == 0: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.green) elif i == 1: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.red) elif i == 2: slice_.setExploded() slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.yellow) elif i == 3: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.magenta) elif i == 4: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.cyan) elif i == 5: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.blue) elif i == 6: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.darkYellow) elif i == 7: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.darkRed) self.chart.addSeries(series)
class DonutBreakdownChart(QChart): def __init__(self, parent=None): super(DonutBreakdownChart, self).__init__(parent) self.mainSeries = QPieSeries() self.mainSeries.setPieSize(0.7) self.addSeries(self.mainSeries) def addBreakdownSeries(self, series, color): # Add breakdown series as a slice to center pie. slice = self.mainSeries.append(series.name(), series.sum()) # Customize the slice. slice.setBrush(color) slice.setLabelVisible() slice.setLabelColor(Qt.white) slice.setLabelPosition(QPieSlice.LabelInsideHorizontal) # Position and customize the breakdown series. series.setPieSize(0.8) series.setHoleSize(0.7) series.setLabelsVisible() color = QColor(color) for slice in series.slices(): color = color.lighter(115) slice.setBrush(color) slice.setLabelFont(QFont("Arial", 8)) # Add the series to the chart. self.addSeries(series) # Recalculate breakdown donut segments. self.recalculateAngles() def recalculateAngles(self): angle = 0.0 for slice in self.mainSeries.slices(): series = self.find(slice.label()) if series is not None: series.setPieStartAngle(angle) angle += slice.percentage() * 360.0 series.setPieEndAngle(angle) def find(self, seriesName): for series in self.series(): if isinstance(series, QPieSeries) and series.name() == seriesName: return series return None
def create_piechart(self): z=self.dataset w=z.iloc[:,-1] r=w.value_counts() p=r.to_numpy() y=w.nunique() df_val_counts = pandas.DataFrame(r) df_val_counts = df_val_counts.reset_index() df_val_counts.columns = ['unique_values', 'counts'] w=df_val_counts.iloc[:,0].to_numpy() k=df_val_counts.iloc[:,1].to_numpy() res = w.astype(str) series = QPieSeries() for i in range(y): series.append(res[i], k[i]) chart = self.chartView.chart() chart.removeAllSeries() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.AllAnimations) chart.setTitle("Pie Chart") chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) #self.chartView = QChartView(chart) self.chartView.setRenderHint(QPainter.Antialiasing)
def createPieChart(self): chart = QChart() chart.setTitle("Pie chart") pieSize = 1.0 / len(self.m_dataTable) for i, data_list in enumerate(self.m_dataTable): series = QPieSeries(chart) for value, label in data_list: slice = series.append(label, value.y()) if len(series) == 1: slice.setLabelVisible() slice.setExploded() hPos = (pieSize / 2) + (i / float(len(self.m_dataTable))) series.setPieSize(pieSize) series.setHorizontalPosition(hPos) series.setVerticalPosition(0.5) chart.addSeries(series) return chart