[英]Matplotlib plot shows 2 labels on the y-axis
我正在尝试在 matplotlib 中生成一个连续生成的图。 我面临的问题与右侧 y 轴上的标签有关。 显示的范围是我想要的,但是还有一个附加的标签 (0, 0.2, ... 1,0)。
def doAnimation():
fig, ax = plt.subplots()
def animate(i):
data=prices(a,b,c) #this gives a DataFrame with 2 columns (value 1 and 2)
plt.cla()
ax.plot(data.index, data.value1)
ax2 = ax.twinx()
ax2.plot(data.index, data.value2)
plt.gcf().autofmt_xdate()
plt.tight_layout()
return ax, ax2
call = FuncAnimation(plt.gcf(), animate, 1000)
return call
callSave = doAnimation()
plt.show()
任何想法如何摆脱设置:0.0、0.2、0.4、0.6、0.8、1.0?
plt.cla
清除当前坐标区。 第一次调用plt.cla
时,当前轴是ax
( ax2
尚不存在)。 清除这些轴会将ax
的 x 和 y 范围重置为 (0,1)。 但是,在第 8 行,您绘制到ax
,并且两个范围都进行了适当调整。
在第 9 行,您创建了一组新轴并将它们命名为ax2
。 当您离开animate
函数时,名称ax2
将超出范围,但它所引用的坐标区对象将保持不变。 这些轴现在是当前轴。
第二次调用 animate 时, plt.cla
清除这些轴,将 x 和 y 范围重置为 (0,1)。 然后,在第 9 行,您创建了一组新轴并将它们命名为ax2
。 这些轴与以前的轴不同! ax2
实际上是指第三组轴,下次调用plt.cla
时将清除它。 每次对动画的新调用都会生成一组新的轴。 有问题的轴标签似乎是粗体的; 事实上,它们已经被画了一千次了。
最简单(更改最少)的修复方法是将ax2 = ax.twinx()
移到animate
之外,并将plt.cla
替换为对ax.cla
和ax2.cla
的单独调用。
我认为更好的方法是在animate
之外创建线条,并在animate
中修改它们的数据。 当我们这样做的时候,让我们将那些对plt.gcf()
的引用替换为对fig
的引用,并通过plt.subplots
tight_layout
将上述变化放在一起,我们得到,
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
import numpy as np
def dummy_prices():
samples = 101
xs = np.linspace(0, 10, samples)
ys = np.random.randn(samples)
zs = np.random.randn(samples) * 10 + 50
return pd.DataFrame.from_records({'value1': ys, 'value2': zs}, index=xs)
def doAnimation():
fig, ax = plt.subplots(1, 1, tight_layout=True)
fig.autofmt_xdate()
ax2 = ax.twinx()
data = dummy_prices()
line = ax.plot(data.index, data.value1)[0]
line2 = ax2.plot(data.index, data.value2, 'r')[0]
def animate(i):
data = dummy_prices()
line.set_data(data.index, data.value1)
line2.set_data(data.index, data.value2)
return line, line2
animator = FuncAnimation(fig, animate, frames=10)
return animator
def main():
animator = doAnimation()
animator.save('animation.gif')
if __name__ == '__main__':
main()
animation.gif
应该看起来像,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.