我在python中有一个动画条形图,我想在其中显示每帧x轴上每个条形的高度。为此,我使用 set_xticklabels 来重置 xtick。它实际上工作得很好,但有一个例外:如果我运行动画并且柱数为>8,则只显示一半的 xtickslabel。所以我的问题是:如何在动画中设置 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()
感谢您的帮助!
请注意,刻度和刻度标签之间存在差异。当将已知数量的刻度标签设置为未知数量的刻度时,结果可以是任何内容。
为了确保每个柱都有自己的刻度标签,我们可以将刻度设置为柱的位置。
ax.set_xticks(range(l))
然后,我们可以将刻度标签设置为我们想要的任何内容,但当然,我们需要与刻度一样多的刻度标签。
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()