Search code examples
pythonpyside2qtcharts

How to change the color of a graph in PySide2


I'm making a simple graph in PySide2 and was just wondering if you can change the color to something else. This is currently my code.

series = QtCharts.QLineSeries()

series.append(0,0)
series.append(1,7)
series.append(1.2,14)
series.append(1.3,21)
series.append(1.4,28)
series.append(1.5,35)

self.chartView = QtCharts.QChartView(self)
self.chartView.chart().addSeries(series)
self.chartView.chart().createDefaultAxes()
self.chartView.resize(600, 480)

Any help would be great


Solution

  • If you want to change the color of the line you must set it with setColor():

    from PySide2 import QtGui, QtWidgets
    from PySide2.QtCharts import QtCharts
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
    
            series = QtCharts.QLineSeries()
            series.append(0,0)
            series.append(1,7)
            series.append(1.2,14)
            series.append(1.3,21)
            series.append(1.4,28)
            series.append(1.5,35)
    
            self.chartView = QtCharts.QChartView()
            self.chartView.chart().addSeries(series)
            self.chartView.chart().createDefaultAxes()
            self.setCentralWidget(self.chartView)
            series.setColor(QtGui.QColor("salmon"))
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.resize(640, 480)
        w.show()
        sys.exit(app.exec_())
    

    enter image description here

    If you want to change the background color you must use the setCackgroundBrush() method of QChart():

    self.chartView.chart().setBackgroundBrush(QtGui.QColor("gray"))
    

    enter image description here