pyqt用QWidget和QtChart库实现显示柱状图
时间: 2024-06-05 22:07:02 浏览: 219
以下是一个使用QWidget和QtChart库显示柱状图的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtChart import QChart, QChartView, QBarSet, QBarSeries, QBarCategoryAxis
class BarChart(QWidget):
def __init__(self):
super().__init__()
# 创建数据集
set0 = QBarSet("Set 0")
set1 = QBarSet("Set 1")
set2 = QBarSet("Set 2")
set3 = QBarSet("Set 3")
set4 = QBarSet("Set 4")
set5 = QBarSet("Set 5")
set0 << 1 << 2 << 3 << 4 << 5 << 6
set1 << 5 << 0 << 0 << 4 << 0 << 7
set2 << 3 << 5 << 8 << 13 << 8 << 5
set3 << 5 << 6 << 7 << 3 << 4 << 5
set4 << 9 << 7 << 5 << 3 << 1 << 2
set5 << 0 << 0 << 0 << 0 << 0 << 10
# 创建柱状图系列
series = QBarSeries()
series.append(set0)
series.append(set1)
series.append(set2)
series.append(set3)
series.append(set4)
series.append(set5)
# 创建图表和图表视图
chart = QChart()
chart.addSeries(series)
chart.setTitle("Bar Chart Example")
chart.setAnimationOptions(QChart.SeriesAnimations)
chart.legend().setVisible(True)
chart.legend().setAlignment(Qt.AlignBottom)
# 创建X轴和Y轴
axisX = QBarCategoryAxis()
axisX.append(["Jan", "Feb", "Mar", "Apr", "May", "Jun"])
chart.addAxis(axisX, Qt.AlignBottom)
series.attachAxis(axisX)
axisY = chart.createDefaultAxes()
axisY[0].setTitleText("Value")
# 创建图表视图
chartView = QChartView(chart)
chartView.setRenderHint(QPainter.Antialiasing)
# 设置窗口属性
self.setWindowTitle("Bar Chart Example")
self.setGeometry(100, 100, 600, 400)
# 布局管理器
layout = QVBoxLayout()
layout.addWidget(chartView)
# 设置窗口布局
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
barChart = BarChart()
barChart.show()
sys.exit(app.exec_())
```
运行代码,将会弹出一个窗口,显示一个柱状图,如下图所示:
![bar_chart_example.png](https://cdn.jsdelivr.net/gh/kainhuck/blog_images/images/bar_chart_example.png)
阅读全文