Home > database >  Matplotlib draw line on image and set axis val
Matplotlib draw line on image and set axis val

Time:10-14

Can anyone show me how to create image like that using Python? I did draw a line but I dont know how to change x and y value.

Input:

enter image description here

Output:

enter image description here

from matplotlib import image
from matplotlib import pyplot as plt


# to read the image stored in the working directory
data = image.imread('Darwin_Maps.png')

# to draw a line from (200, 300) to (500, 100)
x = [200, 500]
y = [300, 100]
plt.plot(x, y, color="white", linewidth=3)
plt.imshow(data)
plt.show()

CodePudding user response:

You can use range to draw you lines in a loop:

from matplotlib import image
from matplotlib import pyplot as plt

data = image.imread('Darwin_Maps.png')
img_height, img_width, _ = data.shape

x_space = 120 #this is in pixel, you might want to change it depending on the scale of your map
x_space_km = 5
y_space = 120 #this is in pixel, you might want to change it depending on the scale of your map
y_space_km = 5

xlabel = x_space_km
for x in range(x_space, img_width, x_space):
  plt.plot([x, x], [0, img_height], color="white", linewidth=3)
  plt.text(x, 40, xlabel, color="red")
  xlabel  = x_space_km

ylabel = y_space_km
for y in range(x_space, img_height, y_space):
  plt.plot([0, img_width], [y, y], color="white", linewidth=3)
  plt.text(40, y, ylabel, color="red")
  ylabel  = y_space_km

plt.imshow(data)
plt.show()

Output:
enter image description here

  • Related