Skip to content

Instantly share code, notes, and snippets.

@DataSolveProblems
Created August 21, 2019 03:46
Show Gist options
  • Save DataSolveProblems/b1070762237dd04eb11991bbd27c70c0 to your computer and use it in GitHub Desktop.
Save DataSolveProblems/b1070762237dd04eb11991bbd27c70c0 to your computer and use it in GitHub Desktop.
import sys, random
from PyQt5.QtWidgets import (QApplication, QMainWindow)
from PyQt5.QtChart import QChart, QChartView, QValueAxis, QBarCategoryAxis, QBarSet, QBarSeries
from PyQt5.Qt import Qt
from PyQt5.QtGui import QPainter
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.resize(800, 600)
set0 = QBarSet('X0')
set1 = QBarSet('X1')
set2 = QBarSet('X2')
set3 = QBarSet('X3')
set4 = QBarSet('X4')
set0.append([random.randint(0, 10) for i in range(6)])
set1.append([random.randint(0, 10) for i in range(6)])
set2.append([random.randint(0, 10) for i in range(6)])
set3.append([random.randint(0, 10) for i in range(6)])
set4.append([random.randint(0, 10) for i in range(6)])
series = QBarSeries()
series.append(set0)
series.append(set1)
series.append(set2)
series.append(set3)
series.append(set4)
chart = QChart()
chart.addSeries(series)
chart.setTitle('Bar Chart Demo')
chart.setAnimationOptions(QChart.SeriesAnimations)
months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun')
axisX = QBarCategoryAxis()
axisX.append(months)
axisY = QValueAxis()
axisY.setRange(0, 15)
chart.addAxis(axisX, Qt.AlignBottom)
chart.addAxis(axisY, Qt.AlignLeft)
chart.legend().setVisible(True)
chart.legend().setAlignment(Qt.AlignBottom)
chartView = QChartView(chart)
self.setCentralWidget(chartView)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
@vinuraj-ign
Copy link

what if I need only one bar in each section. i.e, single bar graph. I know there is BarGraphItem but I am unable to change the x-values to string there.

@elKuston
Copy link

I am in the very same situation right now. Did yoy find a solution? I followed this script creating just one series and it did work, but doesn't feel like the best way to go. For some reason everyone on the internet uses this same example hahaha.

This is what I got:
image

@vinuraj-ign
Copy link

Using only one set solved my requirement. Looks like your chart is good enough. There is nothing wrong with that.

@elKuston
Copy link

Yeah the chart itself looks good, i was just wondering if there was an "easier" way to do it hahaha. Thanks for your help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment