如何在python Matplotlib中获取条形图的关联轴

2024-09-26 22:54:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过实践学习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()的方法,但不起作用)。在网上我也找不到答案。 如何从图形或任何子对象(我猜图形是轴的子对象)中获取相关轴? This is the junk I got!!


Tags: 对象import图形forgetasnpfig
2条回答

您可以直接使用ax.text(x, y, s, ...)see here):

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')

我会帮你的

enter image description here

现在,您可以增加figsize,然后相应地更改字体大小以获得更好看的图形(如果您单击它):

# Parameters for picture below:
figsize=(20, 12)
fontsize='large'
str(np.round(y, 2)) + '%'

enter image description here

我不确定这是否可行,因为对象matplotlib.patches.Rectange(即单个条)需要在层次结构中具有向上的类关系(figure=>;axes=>;lines)

标准程序是了解轴:

import matplotlib.pyplot as plt
import numpy as np
# create dummy data
rns = np.random.randn(50)
# open figure
fig,(ax1,ax2) = plt.subplots(2,1,figsize=(10,6))
# bar charts
barg1 = ax1.bar(range(50),rns)
barg2 = ax2.bar(range(50),rns**2)

# define function
def anotateBarChart(ax,BargChart):
    for bar in BargChart:
        reading = round(bar.get_height(),2)
        ax.annotate(str(reading)+'%',(bar.get_x(),reading))

# call defined function
anotateBarChart(ax1,barg1)
anotateBarChart(ax2,barg2)

我已经创建了一个小函数,这样您就不需要在它们上面连接线+循环,而只需要在每个axis对象上调用一个函数。此外,我建议使用^{}而不是text,但这只是一个提示

enter image description here

相关问题 更多 >

    热门问题