0

I like to create a simple bar chart with QChart. I found a lot of tutorials with series in the bars, like this https://codeloop.org/qt5-tutorial-creating-barchart-with-qtchart/. But I don't need series, just a bar per month with a value, like this:

enter image description here

Where can I find a tutorial for such a chart?

Thanks

Marlowe
  • 252
  • 3
  • 15

1 Answers1

0

I found a way to do it. Here is a code to create the chart with data from a list.

def show_reports_by_year(self):
    # get the data
    year_list = self.get_cases_by_year()
    years = []
    reports = []
    for year in year_list:
        years.append(year[0])
        reports.append(year[1])

    # create the chart
    chart = QChart()
    chart.setAnimationOptions(QChart.SeriesAnimations)
    chart.setTheme(QChart.ChartThemeBlueIcy)
    
    # set font for chart title
    font = QFont()
    font.setPixelSize(20)
    chart.setTitleFont(font)
    chart.setTitle("Cases per year")

    #data to series and put to chart
    cases_max = []
    i = 0
    for year in year_list:
        series = QBarSeries()
        curr_set = "set" + str(i)
        curr_set = QBarSet(str(year[0]))
        curr_set << int(year[1])
        series.append(curr_set)
        series.setLabelsVisible(True)
        series.labelsPosition()
        chart.addSeries(series)
        cases_max.append(int(year[1]))

        i += 1

    #create axis
    axisX = QBarCategoryAxis()
    axisX.setLabelsVisible(True)
    axisX.append(years)

    axisY = QValueAxis()
    axisY.setLabelsVisible(True)
    axisY.setMin(0)
    axisY.setMax(max(reports))
    axisY.setLabelFormat("%.0f")
    axisY.setTitleText("Reports")

    # bild the chart
    chart.createDefaultAxes()
    chart.legend().hide()
    chart.setAxisX(axisX)
    chart.setAxisY(axisY)

    # create view
    chartview = QChartView(chart)
    vbox = QVBoxLayout()
    vbox.addWidget(chartview)

    # put view to qt grid layout
    self.ui.gridLayout.addWidget(chartview,0,0)

enter image description here

Marlowe
  • 252
  • 3
  • 15