在tkinter Python上使用matplotlib绘制线时出错

2024-09-29 00:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我用tkinter编写了一个程序,它从treeview获取值,将它们放入numpy数组列表(Xprojekti, Yprojekti),然后在tkinter窗口上绘制图形。 这两个列表中的值不是按顺序排列的,但我想将它们打印出来,以便轴上的值按顺序排列。当我尝试这样做时,会出现以下错误:

    for seg in self._plot_args(this, kwargs):
  File "C:\Python36-32\lib\site-packages\matplotlib\axes\_base.py", line 384, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "C:\Python36-32\lib\site-packages\matplotlib\axes\_base.py", line 243, in _xy_from_xy
    "have shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y must have same first dimension, but have shapes (50,) and (3,)

我该怎么办

Xprojekti=np.array([])
Yprojekti=np.array([])

for child in tree.get_children():
    ProjectSize=round(float(tree.item(child,"values")[1]),2)
    Xprojekti=np.append(Xprojekti, ProjectSize)

for child in tree.get_children():
    ProjectCost=round(float(tree.item(child,"values")[3]),2)
    Yprojekti=np.append(Yprojekti, ProjectCost)

X=np.linspace(np.min(Xprojekti), np.max(Xprojekti))  # I used this to sort the values on X

fprojekti=Figure(figsize=(6.5, 4.2),dpi=83)
grafikprojekti=fprojekti.add_subplot(111)

grafikprojekti.plot(X, Yprojekti, color="blue",marker="o", linewidth=1)
grafikprojekti.set_xlabel("Size")
grafikprojekti.set_ylabel("Costs")
grafikprojekti.set_title("All projects")
grafikprojekti.grid()

canvasprojects=FigureCanvasTkAgg(fprojekti, master=Database)
canvasprojects.show()
canvasprojects.get_tk_widget().grid(row=1,column=2,sticky="wn",padx=5)

toolbar_frameprojekti=Frame(Database)
toolbar_frameprojekti.grid(row=2,column=2,sticky="wn",padx=5)

toolbarprojects = NavigationToolbar2TkAgg(canvasprojects,toolbar_frameprojekti)
toolbarprojects.update()
canvasprojects._tkcanvas.grid(row=1,column=2,sticky="wn",padx=5,pady=10)

Tags: andinchildtreeforgetplothave
1条回答
网友
1楼 · 发布于 2024-09-29 00:23:15

函数linspace不是排序函数。它返回指定间隔内的等距数字(请参见documentation)。解决问题的最简单方法是:

  1. 从树中提取元组列表(x,y)
  2. 排序此列表
  3. 按照正确的顺序创建x和y列表

下面的代码应该可以做到这一点(未经测试,因为我没有tree对象)

# Get a list of points
points = []
for child in tree.get_children():
    points.append((float(tree.item(child,"values")[1]), 
                   float(tree.item(child,"values")[3])))
# Sort the points
points = sorted(point)
# Extract X and Y 
X = [v[0] for v in points]
Y = [v[1] for v in points]
# And now the rest of our code
projekti=Figure(figsize=(6.5, 4.2),dpi=83)
grafikprojekti=fprojekti.add_subplot(111)
grafikprojekti.plot(X, Y, color="blue",marker="o", linewidth=1)

一些评论:

  1. 我没有把数值四舍五入到两位小数,我想你不需要它
  2. 排序列表是有效的,因为排序元组列表时,首先比较元组的第一个元素
  3. 在可能的情况下,最好一次遍历结构,以确保保持顺序

相关问题 更多 >