In this Python PySide6 lesson we want to learn How to Create BarChart with Python & PySide6, Bar charts are an effective way to visualize categorical data and it makes it easy to compare the values of different groups. In this lesson we are going to explore how to create simple bar chart in Python PySide6 using the QtCharts module.
This is the complete code for this lesson
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
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,QBarSeries, QBarSet, QBarCategoryAxis, QValueAxis class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("GeeksCoders BarChart 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 Monthly Sales") chart.setAnimationOptions(QChart.SeriesAnimations) series = QBarSeries() series.setName("Sales Data") sales_data = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65] months = range(1, 13) set0 = QBarSet("Sales") for i in range(12): set0.append(sales_data[i]) series.append(set0) chart.addSeries(series) # Add axes to the chart axis_x = QBarCategoryAxis() axis_x.append(months) chart.addAxis(axis_x, Qt.AlignBottom) series.attachAxis(axis_x) axis_y = QValueAxis() axis_y.setLabelFormat("%i") axis_y.setTitleText("Sales") chart.addAxis(axis_y, Qt.AlignLeft) series.attachAxis(axis_y) # 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 defined custom MainWindow class that extends from QMainWindow and create the main widget and layout.
after that we have created QChartView instance that will display the BarChart and add it to the layout. we also created QChart instance and set its title and animation options. Then, we create a QBarSeries instance and populate it with the sales_data array using QBarSet instance.
after that we have added QBarSeries instance to the QChart instance using the addSeries method. we also added QBarCategoryAxis instance for the X-axis and QValueAxis instance for the Y-axis, and attach them to the QBarSeries using the attachAxis method.
and finally we set 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