user1551817
user1551817

Reputation: 7451

plotting imshow and line plot together in python

Okay I'm totally stuck with a Python problem. I think describing the problem in too much detail is confusing, so I will summarise the problem and then show the code I have.

I have created an imshow plot, over the top of which, I would like to plot a regular line plot. The Y axis is different, which is fine, but the X axes should be the same for both.

It almost works, apart from the scaling:

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xlabel('MJD',fontsize=14)
ax1.set_ylabel('Bin Number',fontsize=14)
mjdaxis=np.linspace(0,bad_removed_mjd.shape[0]-1,20).astype('int')
ax1.set_xticks(mjdaxis,[int(np.floor(bad_removed_mjd[i])) for i in mjdaxis])
ax1.imshow(residuals, aspect="auto")

ax2 = ax1.twinx()
ax2.set_ylabel('Pdot (s-2)',fontsize=14)
ax2.plot(pdot[8:,0],pdot[8:,1])

plt.show()

Now what happens is that the imshow plot gets squashed between values 0-60 or so on the x axis. This is because they are now getting plotted by their index number 0,1,2.... I need their x axis values to correspond to the value in the list 'bad_mjd_removed' 55304, 55365, 55401.... This works fine when I just have the imshow plot on its own.

Here are pictures of the imshow plot on its own, and then when I try to add the line plot over it:

plot with imshow only plot with imshow and line plot

On the second plot, the thin line at around 0 on the x axis is the whole of picture 1 squeezed inbetween 0 and 60.

I would be very grateful of any help on this problem. Thank you.

Upvotes: 2

Views: 4870

Answers (2)

wim
wim

Reputation: 362557

You can use extent kwarg to put your imshow plot in the right place. As an added bonus, you should be able to let matplotlib handle the axis tickmarks automatically if you've done this too.

import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(2,3)
plt.imshow(x, interpolation='nearest', extent=[0,3,0,2])

enter image description here

plt.imshow(x, interpolation='nearest', extent=[100,103,100,102])

enter image description here

Upvotes: 3

sega_sai
sega_sai

Reputation: 8538

One possibility for you is to use extend= keyword of imshow, e.g.

plt.imshow(extend=(mjdaxis.min(),0,mjdaxis.max(),1000)

or something like that. But you should also keep in mind that if the gaps between the mjdaxis tickmarks are not constant your line-plot won't directly correspond to the image, because the imshow plot won't be stretched in the same way as the line plot

Upvotes: 0

Related Questions