How to get the associated axis of a bar chart in python Matplotlib

故事扮演 提交于 2021-02-11 12:55:23

问题


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


回答1:


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




回答2:


I am not sure if that is possible, because the object matplotlib.patches.Rectange (that is a single bar) would need to have a class relation upwards in hierarchy (figure => axes => lines)

The standard procedure is to know the axis:

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)

I have created a small function, so that you don't need to concatenate the lines + loop over them but can just call a function on each axis object. Further, I recommend to use annotate rather than text, but is just a hint



来源:https://stackoverflow.com/questions/65211861/how-to-get-the-associated-axis-of-a-bar-chart-in-python-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!