简体   繁体   中英

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:

仅使用 imshow 绘图用 imshow 和线图绘制

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.

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])

在此处输入图片说明

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

在此处输入图片说明

One possibility for you is to use extend= keyword of imshow, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM