set_xticklabels在动画条形图中

时间:2017-03-19 19:24:19

标签: python matplotlib

我在python中有一个动画条形图,我想在每个帧的x轴上显示每个条形的高度。为此,我使用set_xticklabels重置xticks。它实际上很好用,但有一个例外:如果我运行动画并且条数> 8,那么只显示一半的xtickslabels。所以我的问题是:如何在动画中设置xticks的步长,这样无论有多少条都可以看到所有这些?下面是一个最小的演示方法(有一些评论,希望有用)。请尝试使用不同数量的条形图(存储在变量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()

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

请注意,刻度线和刻度标签之间存在差异。当将已知数量的刻度标签设置为未知数量的刻度时,结果可以是任何结果。

为了确保每个条形图都有自己的标签,我们可以将标记设置为条形图的位置。

ax.set_xticks(range(l))

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

ax.set_xticklabels(newxticklabels)

一个完整的工作示例:

import matplotlib.pyplot as plt
from matplotlib import animation

n=100 #number of frames
l=13  #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))  
barchart=ax.bar(range(l),barlist,align='center')
ax.set_xticks(range(l))

def animate(i):
    y=test_func(i)
    newxticklabels=[]
    for j,x in enumerate(y):
        newxticklabels.append(round(x,3))
    ax.set_xticklabels(newxticklabels)
    for j,h in enumerate(barchart):
        h.set_height(y[j])

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