Home > Software design >  How to replace Matplotlib bar patches with an exact same size image?
How to replace Matplotlib bar patches with an exact same size image?

Time:11-07

How to replace Matplotlib bar patches with an exact same size image so that it can be seen more fancy in some way.

I looked up the docs of the Matplotlib Patch, it seems that it can just set face color or edge color, but no way to set an image. Also tried the AnnotationBBox, it seems that the params of position can be set but not the size. Maybe I should reset the image to the proper size first? enter image description here

What the graph shown is something close to what I want, but the position and the size are not quite fit. Any elegant solution? Thanks in advance.

CodePudding user response:

Instead of trying to change the bars, you can plot the bars unfilled and then just put the image you want on top of each bar (using imshow).

For instance:

import matplotlib.pyplot as plt
       
fig, ax = plt.subplots()

# a single bar with some random data
bar = ax.barh([0,],[90,],fill=False) # note the fill set to false
ax.set_yticks([0,])
ax.set_yticklabels(("Portugal",))

plt.title("one bar")

# lets set the limits so that they dont get changed
ax.set_xlim([0,200])
ax.set_ylim(ax.get_ylim())

for b in bar: # in this example we only have one bar

    #uncomment this to disable the imshow for this example and see the plot without the flag
    #break
    
    img = plt.imread("f_pt.png") # a png with a flag
    
    #get the position of the bar, but not the bar itself
    #this is to tell imshow where to put the image
    b_h, b_w = b.get_height(), b.get_width()
    b_x, b_y = b.get_x(), b.get_y()       
    left, right = (b_x), (b_x   b_w)
    bottom, top = (b_y), (b_y   b_h)

    # note that this is not acting on the bar itself, but doing imshow on the location of the bar   
    ax.imshow(img, extent = [left, right, bottom, top],
                aspect = "auto")

plt.show()

Result: enter image description here

  • Related