问题描述
试图创建饼形图,但由于某种原因,我无法使其正确连接在一起.当我运行代码时,它会在彼此之上创建许多段.这是我的代码:
Trying to create a pie chart shape but for some reason I can't get it to join together correctly. When I run my code It creates a lot of segments on top of each other.Here is my code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, random
app = QApplication(sys.argv)
scene = QGraphicsScene()
families = [1,2,3,4,5,6,7]
total = 0
colours = []
set_angle = 0
count1 = 0
total = sum(families)
for count in range(len(families)):
number = []
for count in range(3):
number.append(random.randrange(0, 255))
colours.append(QColor(number[0],number[1],number[2]))
for family in families:
angle = round(family/total*16*360)
ellipse = QGraphicsEllipseItem(0,0,400,400)
ellipse.setPos(0,0)
ellipse.setStartAngle(set_angle)
ellipse.setSpanAngle(angle)
ellipse.setBrush(colours[count1])
set_angle = angle
count1 +=1
scene.addItem(ellipse)
view = QGraphicsView(scene)
view.show()
app.exec_()
推荐答案
挖该线程可能会有所帮助.@Barry的答案几乎是正确的,但需要进行一些调整.
Digging this thread as it might help others.@Barry's answer is almost correct, but needs a few adjustments.
实际上,要使椭圆具有完美的圆形,您需要更改线条:
Indeed, to have a perfect round shape to your ellipse, you need to change the line:
set_angle = angle
到
set_angle += angle
这样,set_angle
(这是我们的饼块"的起始角度)始终是在画布上绘制的最后一个角度.
This way, the set_angle
(which is the starting angle of our "pie chunks") is always the last angle drawn on the canvas.
还行:
angle = round(family/total*16*360)
可以这样写(出于可读性考虑):
could be written like this (for readability's sake):
angle = round(float(family*(16*360))/total)
因此,一个可行的示例是(使用Python3& PyQt5):
So a working example would be (using Python3 & PyQt5):
from PyQt5.QtWidgets import QGraphicsScene, QApplication, QGraphicsView, QGraphicsEllipseItem
from PyQt5.Qt import QColor
import sys, random
app = QApplication(sys.argv)
scene = QGraphicsScene()
families = [1,2,3,4,5,6,7,8,9,10]
total = 0
set_angle = 0
count1 = 0
colours = []
total = sum(families)
for count in range(len(families)):
number = []
for count in range(3):
number.append(random.randrange(0, 255))
colours.append(QColor(number[0],number[1],number[2]))
for family in families:
# Max span is 5760, so we have to calculate corresponding span angle
angle = round(float(family*5760)/total)
ellipse = QGraphicsEllipseItem(0,0,400,400)
ellipse.setPos(0,0)
ellipse.setStartAngle(set_angle)
ellipse.setSpanAngle(angle)
ellipse.setBrush(colours[count1])
set_angle += angle
count1 += 1
scene.addItem(ellipse)
view = QGraphicsView(scene)
view.show()
app.exec_()
希望有帮助.
这篇关于如何在python中使用pyqt创建饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!