如何在python Matplotlib中获取条形图的关联轴 [英] How to get the associated axis of a bar chart in python Matplotlib
问题描述
我正在通过实践学习 Matplotlib,并在一个图中创建了 2 个子图并绘制了两个条形图.我尝试使用文本函数使用 2 个嵌套 for 循环添加高度.这是代码:
将 numpy 导入为 np导入matplotlib.pyplot作为pltrns = np.random.randn(50)图,(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)对于 [barg,barg2] 中的 bargr:对于 bargr 中的 bar:阅读=圆(bar.get_height(),2)plt.text(bar.get_x(),reading,str(reading)+'%')
但是,正如您可能已经注意到的那样,在 for
循环中,我需要找出与每个条形图关联的axis对象.(我尝试了类似 bargr.get_axes()
的方法,该方法无法正常工作).在网上我也找不到答案.如何从图形或任何子对象中获取关联的轴(我猜图形是轴的子对象)?
您可以使用 ax.text(x, y, s, ...)
(
您现在可以增加 figsize
,然后相应地更改字体大小以获得更好的外观(如果您单击它):
# 下图参数:figsize=(20, 12)fontsize ='大'str(np.round(y, 2)) + '%'
I am learning Matplotlib through practice and have created 2 subplots in a figure and drew two bar charts. I tried adding the height using text function using 2 nested for loops. Here's the code:
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)+'%')
But, as you might have noticed, inside the for
loop, I need to find out the axes object associated with each bar chart. (I tried something like bargr.get_axes()
which is not working) . In net also I couldn't find an answer.
How to get the associated axes from a graph or any child object (I guess graphs are children of axes)?
You can use ax.text(x, y, s, ...)
(see here) directly:
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)
for x, y in zip(range(50), rns):
ax1.text(x, y, str(np.round(y, 1)) + '%', ha='center', rotation='vertical', fontsize='small')
ax2.text(x, y**2, str(np.round(y, 1)) + '%', ha='center', rotation='vertical', fontsize='small')
will get you
You could now increase the figsize
and then change the fontsize accordingly to get a better looking figure (if you click on it):
# Parameters for picture below:
figsize=(20, 12)
fontsize='large'
str(np.round(y, 2)) + '%'
这篇关于如何在python Matplotlib中获取条形图的关联轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!