3

No matter what values I change it's always distorting it, or it's too far on the left.

Here's an example:

Plot with background image

barchart = pd.read_csv('barchart.csv')
df = pd.DataFrame(barchart)
var1 = df['col1'].head(7).tolist()
var2 = df['col2'].head(7).tolist()
sometitle = df['sometitle'][0]
var2 = [ float(x) for x in var2 ]

y_pos = np.arange(len(var1))
datafile = cbook.get_sample_data('/path/to/watch.jpg', asfileobj=False)
im = image.imread(datafile)

plt.imshow(im, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])

barlist = plt.barh(y_pos, var2, align='center', alpha=0.5)
colors = ["red", "green", "blue", "orange", "pink", "cyan", "yellow"]
for a, b in zip(range(6), colors):
    barlist[a].set_color(b)
plt.yticks(y_pos, var1)

plt.xlabel('a label', color="green", fontsize=9)
plt.title(sometitle + " " + str(now)) 
plt.show()  
user812786
  • 4,302
  • 5
  • 38
  • 50
thinkvitamin
  • 81
  • 1
  • 12
  • Can anyone suggest a way to just add a background image to something like this: matplotlib.org/examples/lines_bars_and_markers/barh_demo.htm‌​l without messing with any of the data in any way. I found a really simple example of how to do this with a scatterplot right here on Stack Overflow: http://stackoverflow.com/a/5073487/6007101 but when I tried it with Barh the image just pushed everything out of the way. – thinkvitamin Aug 23 '16 at 23:55

1 Answers1

1

From the documentation,

extent : scalars (left, right, bottom, top), optional, default: None

The location, in data-coordinates, of the lower-left and upper-right corners. If None, the image is positioned such that the pixel centers fall on zero-based (row, column) indices.

So if you want to put the image at a given x, y with size all in data-coordinates, get the ratio of im.shape and use this to scale. For example,

import matplotlib.pyplot as plt
import numpy as np

val = 3+10*np.random.random(7)  
pos = np.arange(7)+.5

fig,ax = plt.subplots(1,1)

colors = ["red", "green", "blue", "orange", "pink", "cyan", "yellow"]
barlist = ax.barh(pos, val, align='center',alpha=0.5)
for a, b in zip(range(6), colors):
    barlist[a].set_color(b)

im = plt.imread('/path/to/watch.jpg')
x = 4.; y = 0.; size = 7.; xyratio = im.shape[1]/im.shape[0]
ax.imshow(im, zorder=0, extent=[x, x+size , y, y+size*xyratio])

ax.set_xlim([0.,np.max(val)+1.])
ax.set_ylim([0.,np.max(pos)+1.])

plt.show()

which looks like,

enter image description here

Note there is also the issue of whitespace around the image which will cause it to appear away from extents.

You can also do something like set aspect="equal" but must remove the extents.

Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55