0

There are many questions related to adding an image to a plot. However, in all these questions the data plotted on top of the image has the same size. For example, in this question, the scatter point are plotted directly into the picture coordinates.

What I need is something else. I have the following data (example) and the following images that I wish to combine:

fig, axes = plt.subplots(1,3, figsize=(15,6), sharey=True)
axes = axes.flatten()

for ax in axes:
    x = [1,2,3,4,5]
    y = x
    ax.bar(x,y)

enter image description here

fig, axes = plt.subplots(1,3, figsize=(15,6), sharey=True)
axes = axes.flatten()

for ax, im in zip(axes,images):
    ax.imshow(im, alpha=0.5)

enter image description here

Now, if I try to plot the bars and the images unto the same axis, the bars will be so small as to be invisible. See for example the effect of set_xticks.

for ax, im in zip(axes,images):
    x = [1,2,3,4,5]
    y = x
    ax.bar(x,y)
    ax.set_xticks([1,2,3,4,5])
    ax.imshow(im, alpha=0.5)

enter image description here

Question:

How can I plot the data on top of the images? I tried it with a twinx but I couldn't get that working properly.

I tried to rescale the data to fit the size of the images.

def scale_data(data, size):
    return [int(x/max(data)*size) for x in data]

But the imshow function also flips the y-axis. Now, I can flip the image first, then flip the y-axis myself again, rescale all the data so it fits onto the images and then set the proper width of the bars, however this all feels much to complex and I assume there is a much simpler solution that I am simply missing.

What is the best way to achieve the desired behavior?

Mitchell van Zuylen
  • 3,905
  • 4
  • 27
  • 64

1 Answers1

0

If you want to plot the graph on top of the image, use the extent parameter to adjust it. In this case, adjust it to match the x-axis of the bar chart. As an example, we use an image from the official reference. Also, subplots are not part of this assignment, so we have used a single graph.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cbook as cbook

with cbook.get_sample_data('grace_hopper.jpg') as image_file:
    image = plt.imread(image_file)

fig, ax = plt.subplots()
x = [1,2,3,4,5]
y = x
ax.bar(x, y)

im = ax.imshow(image, extent=[0,5.5,0,5.5])

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32