pyqt5 饼图有标题示例,每个区域对应一个标题
时间: 2024-01-20 14:03:02 浏览: 65
Python饼状图的绘制实例
以下是一个使用 Pyqt5 绘制饼图并为每个区域添加标题的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView
from PyQt5.QtGui import QPainter, QColor, QPen, QBrush, QPainterPath
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 500, 500)
self.setWindowTitle("Pie Chart with Titles")
self.data = [20, 30, 10, 40]
self.labels = ["A", "B", "C", "D"]
self.titles = ["Title A", "Title B", "Title C", "Title D"]
self.title = "Pie Chart Example"
self.scene = QGraphicsScene(self)
self.view = QGraphicsView(self.scene, self)
self.view.setGeometry(0, 0, 500, 500)
self.draw_pie_chart()
def draw_pie_chart(self):
total = sum(self.data)
start_angle = 0
color_list = [Qt.red, Qt.green, Qt.blue, Qt.yellow]
for i, value in enumerate(self.data):
angle = value / total * 360
path = QPainterPath()
path.moveTo(250, 250)
path.arcTo(50, 50, 400, 400, start_angle, angle)
path.lineTo(250, 250)
path.closeSubpath()
brush = QBrush(color_list[i % len(color_list)])
pen = QPen(Qt.black, 2)
self.scene.addPath(path, pen, brush)
x = 250 + 200 * 0.5 * (1 + 0.8 * Qt.cos(0.5 * (start_angle + angle) * Qt.pi / 180))
y = 250 - 200 * 0.5 * (1 + 0.8 * Qt.sin(0.5 * (start_angle + angle) * Qt.pi / 180))
self.scene.addText(self.titles[i]).setPos(x, y)
start_angle += angle
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
这段代码会绘制一个带有每个区域标题的饼图,并且你可以自己修改数据、标签和标题来绘制自己想要的饼图。
阅读全文