【发布时间】:2017-08-16 07:07:33
【问题描述】:
我想在我的 PyQt GUI 中嵌入由分析类方法生成的数据饼图。使用 PyPlot 或 PyLab 我已经能够绘制图表,但只能在单独的窗口中。
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
self.compute_initial_figure()
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
上面是应该显示饼图的画布。我想我必须在嵌入图表时使用 self.axes 参数,但我不知道。以下是我迄今为止的饼图代码:
class UsersPlatformPie(MyMplCanvas):
def compute_initial_figure(self):
UsersPerCountry, UsersPerPlatform = Analytics.UsersPerCountryOrPlatform()
labels = []
sizes = []
print UsersPerPlatform
for p, c in sorted(UsersPerPlatform.iteritems()):
labels.append(p)
sizes.append(c)
colors = ['turquoise', 'yellowgreen', 'firebrick', 'lightsteelblue', 'royalblue']
pylab.pie(sizes, colors = colors, labels = labels, autopct = '%1.1f%%', shadow = True)
pylab.title('Users Per Platform')
pylab.gca().set_aspect('1'); pylab.show()
我觉得这是多余的但是下面是widget的建立。
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
...
self.main_widget = QtGui.QWidget(MainWindow)
l = QtGui.QVBoxLayout(self.main_widget)
UPP = UsersPlatformPie(self.main_widget, width=5, height=4, dpi=100)
l.addWidget(UPP)
self.main_widget.setFocus()
MainWindow.setCentralWidget(self.main_widget)
我将此代码基于this。对于这个问题的代码繁重,我深表歉意,但我认为至少前两个部分是必要的。非常感谢有关绘制饼图的新方法或将我的饼图连接到上面的画布的建议。
【问题讨论】:
-
你不应该为显示太多代码而道歉,而应该为没有显示minimal reproducible example而道歉。
-
我没有这样做的原因是这不是一个错误。中间部分确实有效,只是不是以预期的方式。
-
这不是错误,而是不受欢迎的行为。尤其是当您链接到显示正确行为的问题时,确实需要minimal reproducible example 才能重现该问题。
标签: python matplotlib pyqt embed pie-chart