Search code examples
pythonmatplotlibmultiple-axes

Adding bar value to subbar plot when there is a custom tick


I need to add bar value to the right of barh() or top of the plt.bar(). However, I have custom xTicks. How should I do that?

So I have 4 subplot that their x or y ticks are customized, following code iterate well but text position is not correct because of xticks.

import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
[subax.yaxis.set(ticks=range(1,4),ticklabels=['a','b','c']) for ax in axes for subax in ax]
# Data
data=list([([8, 9, 8]), ([23, 26, 2]), ([33,37,33]), ([40, 45, 40])])
barplot=[subax.barh([1,2,3],list(data.pop())) for ax in axes for subax in ax]

for ax in axes:
    for subax in ax:
        count=0
        [[subax.text(rect.get_width()+2,3, str(rect.get_width()))] for rect in barplot[count]]
    count+=1
plt.show()

Thanks.

EDIT:When I try to save it as a picture, text placement becomes worst


Solution

  • The y coordinate of the text needs to coincide with the y coordinate of the bar it has to label. So you cannot put 3 for all texts but instead could e.g. use a loop variable obtain that coordinate.

    I cleaned up your code a bit because it was rather hard to read.

    import matplotlib.pyplot as plt
    fig = plt.figure()
    axes = fig.subplots(nrows=2, ncols=2)
    
    data=list([([8, 9, 8]), ([23, 26, 2]), ([33,37,33]), ([40, 45, 40])])
    barplot=[ax.barh(['a','b','c'],list(data.pop())) for ax in axes.flat]
    
    for i, ax in enumerate(axes.flat):
        for j, rect in enumerate(barplot[i]):
            ax.text(rect.get_width(), j, str(rect.get_width()))
    plt.show()
    

    enter image description here