Reputation: 468
I'm doing illustrations for my paper in python using matplotlib
library. In this illustration I have a lot of lines, polygons, circles etc. But then I also want to insert a .png
image from outside.
Here's what I'm trying to do so far:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
fig, ax = plt.subplots()
plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off')
ax.axis('off')
# drawing circle
ax.add_patch(
plt.Circle((0, 0), 0.5, color = 'black')
)
# drawing polygon
ax.add_patch(
Polygon(
[[0,0], [20, 15], [20, 40]],
closed=True, fill=False, lw=1)
)
# importing image
im = plt.imread("frame.png")
# defining image position/size
rect = 0.5, 0.4, 0.4, 0.4 # What should these values be?
newax = fig.add_axes(rect, anchor='NE', zorder=1)
newax.imshow(im)
newax.axis('off')
ax.set_aspect(1)
ax.set_xlim(0, 60)
ax.set_ylim(0, 40)
plt.show()
So the question is, how do I determine the values for rect = 0.5, 0.4, 0.4, 0.4
? E.g., I want the lower left corner of my .png
to be at the point [20, 15]
and I want its height to be 25
.
This is the resulting image:
But I want this dummy frame to be adjusted to my polygon points, like this (this one's adjusted in photoshop):
P.S. Here is the link to the frame.png
to experiment with.
Upvotes: 4
Views: 5343
Reputation: 2307
can you plot your lines and the picture on the same axis?
for that, use the extent
key in plt.imshow()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
im='d:/frame.png'
img=plt.imread(im)
fig, ax = plt.subplots()
frame_height=25
x_start=20
y_start=15
ax.imshow(img,extent=[x_start,x_start+frame_height,y_start,y_start+frame_height])
ax.add_patch(
Polygon(
[[0,0], [20, 15], [20, 40]],
closed=True, fill=False, lw=1)
)
ax.set_xlim(0, 60)
ax.set_ylim(0, 40)
plt.show()
Upvotes: 2