【问题标题】:Matplotlib plotting repeatedly in loopMatplotlib 在循环中重复绘图
【发布时间】:2017-11-25 02:14:30
【问题描述】:

我正在尝试在 for 循环中进行绘图。 我有点数据pts 字典存储点ID和点坐标。字典rect 存储矩形的 id 以及它连接的点。然后我尝试使用patches.Rectangle 绘制矩形,并使用text 命令将矩形的id 放在其中心。在循环结束时,我正在绘制图形。但是什么都没有被绘制出来。我不明白这里出了什么问题。有什么建议吗?

另外,我们可以用plt.axis([xmin, xmax, ymin, ymax]) 代替fig.add_axes([0,0,30,30])吗?

import matplotlib.pyplot as plt
import matplotlib.patches as patches

plt.close('all')
pts={}
#defining points
pts.update({1:(0,0)})
pts.update({2:(10,0)})
pts.update({3:(10,20)})
pts.update({4:(0,20)})
pts.update({5:(30,0)})
pts.update({6:(30,20)})

#defining rectangle connecting to points
rect={}
rect.update({10:(1,2,3,4)})
rect.update({11:(2,5,6,3)})

#plotting
fig = plt.figure()
ax = fig.add_axes([0,0,30,30])
for i in rect:
    p2=rect[i]
    dx,dy = pts[p2[0]]
    wd = pts[p2[1]][0] - pts[p2[0]][0]
    ht = pts[p2[3]][1] - pts[p2[0]][1]
    midpt = [ (pts[p2[0]][0] + pts[p2[2]][0])/2, (pts[p2[0]][1] + pts[p2[2]][1])/2 ]
    #finding midpoint of points zeroth and second 
    #x_mid= (x_0+x_2)/2 and similar for y_mid
    p = patches.Rectangle((dx,dy), wd,ht,fill=False, clip_on=False)
    ax.add_patch(p)

    plt.text(midpt[0],midpt[1],i,color='k')
else:
    plt.show()  

更新:

我正在使用带有for 循环的else 子句,这是允许的。目的是在 for 循环执行完成后进行绘图。欲了解更多信息,Hidden features of Python

【问题讨论】:

  • 底部有一对时髦的线条;缺少if 吗?
  • @andyg0808 :如果您在谈论if else,情况并非如此。很多人不知道for 循环有可选的else 子句。我选择这种方式是因为plt.show() 将在循环完成后执行。请看stackoverflow.com/questions/101268/…

标签: python matplotlib plot


【解决方案1】:

问题出在线条上

fig = plt.figure()
ax = fig.add_axes([0,0,30,30])

这将创建一个比每个维度中的图形大 30 倍的轴。因此,您只能看到轴的 1./(30*30) = 1 per mille

您可能想要做的是添加一个正常的子图并将其数据范围设置为两个方向上的0..30

fig, ax = plt.subplots()
ax.axis([0,30,0,30])

完整示例:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

plt.close('all')
pts={}
#defining points
pts.update({1:(0,0)})
pts.update({2:(10,0)})
pts.update({3:(10,20)})
pts.update({4:(0,20)})
pts.update({5:(30,0)})
pts.update({6:(30,20)})

#defining rectangle connecting to points
rect={}
rect.update({10:(1,2,3,4)})
rect.update({11:(2,5,6,3)})

#plotting
fig, ax = plt.subplots()
ax.axis([0,30,0,30])
for i in rect:
    p2=rect[i]
    dx,dy = pts[p2[0]]
    wd = pts[p2[1]][0] - pts[p2[0]][0]
    ht = pts[p2[3]][1] - pts[p2[0]][1]
    midpt = [ (pts[p2[0]][0] + pts[p2[2]][0])/2, (pts[p2[0]][1] + pts[p2[2]][1])/2 ]
    #finding midpoint of points zeroth and second 
    #x_mid= (x_0+x_2)/2 and similar for y_mid
    p = patches.Rectangle((dx,dy), wd,ht,fill=False, clip_on=False)
    ax.add_patch(p)

    plt.text(midpt[0],midpt[1],i,color='k')
else:
    plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多