In this Python PySide6 lesson we are going to learn about How to Create DonutChart in Python PySide6, so Donut charts are an effective way to visualize proportions, it is similar to pie charts. however donut charts also have hole in the center and it allows for additional information to be displayed. In this lesson we are going to explore how to create simple donut chart in PySide6 using the QtCharts module.
This is the complete code for creating Donut Chart in Python PySide6
from PySide6.QtCore import Qt
from PySide6.QtGui import QPainter
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PySide6.QtCharts import QChartView, QChart, QPieSeries
self.setWindowTitle("GeeksCoders DonutChart 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()
# Set the central widget
# Add some data to the chart
chart = QChart()
chart.setTitle("GeeksCoders Sales by Region")
series = QPieSeries()
# Set the chart view's chart
# Add a hole to the chart
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
In the above code we have imported necessary modules from PySide6. after that we have defined custom MainWindow class that extends from QMainWindow and creates the main widget and layout.
Next we have created QChartView instance that will display DonutChart and add it to the layout. we also creates QChart instance and set its title and animation options. then we have created QPieSeries instance and add four data points to represent the sales of four regions. we use append method to add each data point to the series.
we have added QPieSeries instance to the QChart instance using the addSeries method. and finally we set QChartView’s chart to the QChart instance and set central widget of the main window to the widget.
we also added hole to the chart by setting theme to QtCharts.QChart.ChartThemeBlueCerulean and disabling the drop shadow, also we have enabled the chart’s legend and set its alignment.
Run the complete code and this will be the result