In this Python PySide6 lesson we want to learn How to Create LineChart in Python PySide6, Creating LineCharts is important part of data visualization, which helps to gain insights into complex data patterns. In this lesson we are going to explore how to create LineCharts in Python using PySide6 library.
As we already know that PySide6 is Python binding of the cross platform GUI toolkit Qt, which provides different widgets for building desktop applications, and for creating LineChart in Python and PySide6 we don’t need to install any third part of library, we can directly use the QtCharts module in PySide6.
This is the complete code for LineChart 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 QChart, QChartView, QLineSeries, QValueAxis
self.setWindowTitle("GeeksCoders LineChart 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()
# Create the chart and add it to the view
chart = QChart()
chart.setTitle("GeeksCoders Monthly Sales")
# Add data to the chart
series = QLineSeries()
sales_data = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65]
months = range(1, 13)
for i in range(12):
# Add axes to the chart
axis_x = QValueAxis()
axis_y = QValueAxis()
# Set the chart view's chart
# Set the central widget
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
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 main widget and layout.
Next we have created QChartView instance that will display the LineChart and add it to the layout. we also have created QChart instance and set its title and animation options. after that we added QLineSeries instance to the chart and populate it with the sales_data and months arrays.
We also added two QValueAxis instances to the chart, one for the X-axis and one for the Y-axis, and attach them to the QLineSeries, and finally we have set the chart view’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