0

Hi All I want to plot vertical lines on a plotted image. I am using ax.vlines() to plot the vertical lines on the image, however the resulting plot clears the image leaving only the vertical lines on the figure as showed in the attached image. Any suggestions to correct this are welcomed. Below is my sample code:

def display_image(img, SavePath):
    vmin, vmax = np.min(img), np.max(img)
    fig, ax = plt.subplots(figsize=(4, 4))
    img = ax.imshow(img, cmap='gray', aspect="auto", extent=[0, image.shape[1], img.shape[0]/10, 0], vmin=vmin, vmax=vmax)
    divider = make_axes_locatable(ax)
    cax    = divider.append_axes("right",size="5%",pad=0.05)
    plt.colorbar(img,ax=ax,cax=cax)
    plt.tick_params(labelsize=6)
    for label in  ax.get_xticklabels()+ax.get_yticklabels():
        label.set_fontsize(6)
    ax.vlines(x=[0, 120, 256],  ymin=2, ymax=0, colors='r')   ## this line plots the 3 vertical lines
    plt.savefig(SavePath+'Image', facecolor=fig.get_facecolor(), 
                        edgecolor=fig.get_edgecolor(), transparent=True)

image

1 Answers1

0

You should set the ymax argument of ax.vlines to the height of the image, because right now you only draw a vertical line from pixels 0 to 2 of your image. The following code works for me (make_axes_locatable(ax) commented out because I don't know what it does):

import matplotlib.pyplot as plt
import numpy as np

img = np.random.random(size=(300, 300))

vmin, vmax = np.min(img), np.max(img)
fig, ax = plt.subplots(figsize=(4, 4))
img_ax = ax.imshow(img, cmap='gray', aspect='auto', vmin=vmin, vmax=vmax)
# divider = make_axes_locatable(ax)
# cax    = divider.append_axes("right",size="5%",pad=0.05)
plt.colorbar(img_ax, ax=ax)  # cax=cax)
plt.tick_params(labelsize=6)
for label in  ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(6)
ax.vlines(x=[0, 120, 256], ymin=0, ymax=img.shape[0] - 1, colors='r')   # this line plots the 3 vertical lines
plt.show()

Produces the following plot:

enter image description here

asdf
  • 1,006
  • 1
  • 9
  • Does not work on my end. From the attached image on my post, you can see that the y-axis has been scaled down from 201 to 2.01 using the ```extent``` variable in the ```imshow``` –  Jun 13 '22 at 22:32
  • I think I have seen the reason. I will get it fixed. Thanks for your input @asdf –  Jun 13 '22 at 22:36