In this Python PySide6 lesson we want to learn about How to Create PieChart in Python PySide6, Pie charts are an effective way to visualize proportions and it makes it easier to compare the relative sizes of different categories. In this lesson we are going to explore how to create simple pie chart in PySide6 using the QtCharts module.
This is the complete code for creating pie chart in Python PySide6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import sys from PySide6.QtCore import Qt from PySide6.QtGui import QPainter from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget from PySide6.QtCharts import QChart, QChartView, QPieSeries class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("GeeksCoders PieChart Example") # Create the main widget and layout widget = QWidget() layout = QVBoxLayout(widget) # Create the chart view and add it to the layout chart_view = QChartView() chart_view.setRenderHint(QPainter.Antialiasing) layout.addWidget(chart_view) # Set the central widget self.setCentralWidget(widget) # Add some data to the chart chart = QChart() chart.setTitle("GeeksCoders Sales by Product") chart.setAnimationOptions(QChart.SeriesAnimations) series = QPieSeries() series.append("Product A", 10) series.append("Product B", 20) series.append("Product C", 30) series.append("Product D", 40) chart.addSeries(series) # Set the chart view's chart chart_view.setChart(chart) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec()) |
In the above code we have imported necessary modules from PySide6. after that we have define custom MainWindow class that extends from QMainWindow and create the main widget and layout.
after that we create QChartView instance that will display PieChart and add it to the layout. we also creates QChart instance and set its title and animation options. after that we create QPieSeries instance and add four data points to represent the sales of four products. we use the append method to add each data point to the series.
we add the QPieSeries instance to the QChart instance using the addSeries method, and finally we set the QChartView’s chart to the QChart instance and set the central widget of the main window to the widget.
Run the complete code and this will be the result