在动画栏中设置“xticklabels”

2024-10-01 04:59:07 发布

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

我有一个用python编写的动画条形图,其中我希望在每一帧的x轴上显示每个条的高度。为此,我使用set xticklabels来重置xtick。它实际上工作得很好,但有一个例外:如果我运行动画,条数是>;8,那么只显示一半的xtickslabels。所以我的问题是:如何在动画中设置xtick的步长,这样无论有多少条条,我都可以看到它们?下面是一个最低限度的示范手段(与一些意见,希望有帮助)。请尝试使用不同数量的条形图(存储在变量l中):

import matplotlib.pyplot as plt
from matplotlib import animation


n=100 #number of frames
l=8  #number of bars

def test_func(k): #just some test function, has no further meaning
    A=[]
    for i in range (l):
        numerator=(i+1)*k
        denominator=(i+k+1)**2+1
        A.append(numerator/float(denominator))
    return A

barlist=[] # the list of bars that is reused in each frame
for i in range(l):
    barlist.append(0)


fig=plt.figure()
ax=plt.axes(xlim=(-1,l),ylim=(0,0.5)) # the ticks are centered below each
                                      # bar; that's why the x-axis starts
                                      # at -1; otherwise you see only
                                      # half of the first bar.
barchart=ax.bar(range(l),barlist,align='center')


def animate(i):
    y=test_func(i)
    newxticks=[''] # since the x-axis starts at -1 but the new xticks
                   # should start at 0, the first entry is set to an
                   # empty string.
    for j,x in enumerate(y):
        newxticks.append(round(x,3))
    for j,h in enumerate(barchart):
        h.set_height(y[j])
        ax.set_xticklabels(newxticks)


anim=animation.FuncAnimation(fig,animate,repeat=False,frames=n,interval=50)
plt.show()

谢谢你的帮助!在


Tags: oftheintestforbarrange动画
1条回答
网友
1楼 · 发布于 2024-10-01 04:59:07

请注意,滴答和滴答标签是有区别的。当将已知数量的ticklabels设置为未知数量的tick时,结果可以是任何内容。在

为了确保每个条都有自己的ticklabel,我们可以将刻度设置为条形的位置。在

ax.set_xticks(range(l))

然后我们可以将ticklabels设置为任何我们想要的,但是我们当然需要尽可能多的ticklabels。在

^{pr2}$

完整的工作示例:

^{3}$

相关问题 更多 >