-1

I have created a graph with matplotlib with data, I would like to add a background image but the data changes depending on the image data. I want this with an image on the background, like this : What I want

So the graphic and the one created by this code :

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = [datetime.datetime(2020, 7, 17, 0, 0) + datetime.timedelta(hours=i) for i in range(24)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
ax = plt.subplot()
ax.plot(x,y, lw=4)
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.gca().set_axisbelow(True)
plt.gca().grid(color='gray', linestyle='dashed')
plt.savefig("chart.png", transparent=True, dpi=80)

But when I try to add an image with this code :

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = [datetime.datetime(2020, 7, 17, 0, 0) + datetime.timedelta(hours=i) for i in range(24)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
ax = plt.subplot()
imageFile = cbook.get_sample_data('/root/image.png')
image = plt.imread(imageFile)
ax.imshow(image)
ax.plot(x,y, lw=4)
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.gca().set_axisbelow(True)
plt.gca().grid(color='gray', linestyle='dashed')
plt.savefig("chart.png", transparent=True, dpi=80)

This gives me this : Wrong graphic

1 Answers1

1

Sample with correct extent values:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

ax = plt.subplot()
x = [datetime.datetime(2020, 7, 17, 0, 0) + datetime.timedelta(hours=i) for i in range(24)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
ax.plot(x, y, lw=4)

img = plt.imread('img.png')
x0,x1 = ax.get_xlim()
y0,y1 = ax.get_ylim()
ax.imshow(img, extent=[x0, x1, y0, y1], aspect='auto')

myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.gca().set_axisbelow(True)
plt.gca().grid(color='gray', linestyle='dashed')

plt.savefig("chart.png", transparent=True, dpi=80)

enter image description here