我通过实践学习Matplotlib,在一个图形中创建了两个子图,并绘制了两个条形图。 我尝试使用文本函数添加高度,使用2个嵌套for循环。代码如下:
import numpy as np
import matplotlib.pyplot as plt
rns = np.random.randn(50)
fig,(ax1,ax2) = plt.subplots(2,1,figsize=(10,6))
barg = ax1.bar(range(50),rns)
barg2 = ax2.bar(range(50),rns**2)
fig.subplots_adjust(hspace=0.6)
for bargr in [barg,barg2]:
for bar in bargr:
reading = round(bar.get_height(),2)
plt.text(bar.get_x(),reading, str(reading)+'%')
但是,正如您可能已经注意到的,在for
循环中,我需要找出与每个条形图关联的axes对象。(我尝试了类似于bargr.get_axes()
的方法,但不起作用)。在网上我也找不到答案。
如何从图形或任何子对象(我猜图形是轴的子对象)中获取相关轴?
您可以直接使用
ax.text(x, y, s, ...)
(see here):我会帮你的
现在,您可以增加
figsize
,然后相应地更改字体大小以获得更好看的图形(如果您单击它):我不确定这是否可行,因为对象
matplotlib.patches.Rectange
(即单个条)需要在层次结构中具有向上的类关系(figure=>;axes=>;lines)标准程序是了解轴:
我已经创建了一个小函数,这样您就不需要在它们上面连接线+循环,而只需要在每个axis对象上调用一个函数。此外,我建议使用^{} 而不是
text
,但这只是一个提示相关问题 更多 >
编程相关推荐