I am trying to plot the following image (Red writing is for illustration only) for these points [[0, 0], [20, 10], [50, 50],[100, 50], [120, 120]] using matplotlib.
The expected result is as follows:
I tried this code
points = [[0, 0], [20, 10], [50, 50],[100, 50], [120, 120]]
# set image size
px = 1/plt.rcParams['figure.dpi']
plt.subplots(figsize=(271*px, 271*px))
ax = plt.gca()
# remove padding
ax.set_position((0, 0, 0, 0))
# set maximum and minimum values
ax.set_xlim([0, 270])
ax.set_ylim([0, 270])
# set background color
plt.axes().set_facecolor('black')
# make axis invisible
#plt.axis('off')
# plotting
for i in range (len(points) - 1):
plt.plot([points[i][0], points[i 1][0]], [points[i][1], points[i 1][1]], color="white")
plt.savefig('testplot.png')
plt.show()
But the resulted image is as follows
For research purposes, I need to make the image exactly follow these requirements:
- Image size 271 px * 271 px
- Without white padding
- Maximum X and Y values are 270
- Image background is black
- One pixel between each step
- Each point in the image represents a pixel
- Invisible axes
CodePudding user response:
This might be what you are looking for:
points = [[0, 0], [20, 10], [50, 50],[100, 50], [120, 120]]
points_x = [i[0] for i in points]
points_y = [i[1] for i in points]
px = 1/plt.rcParams['figure.dpi']
fig = plt.figure(figsize=(271*px, 271*px))
plt.plot(points_x, points_y, color="white")
plt.axes().set_facecolor('black')
plt.xlim([0, 270])
plt.ylim([0, 270])
plt.show()
Splitting the data before plotting can safe you some trouble and adding elements to a 'simplified' version till something breaks is often a good idea.
CodePudding user response:
Finally, I found the solution. The whole requirements are covered as follows:
import matplotlib.pyplot as plt
points = [[0, 0], [20, 10], [50, 50],[100, 50], [120, 120]]
points_x = [i[0] for i in points]
points_y = [i[1] for i in points]
px = 1/plt.rcParams['figure.dpi']
fig = plt.figure(figsize=(571*px, 571*px), facecolor='black')
plt.plot(points_x, points_y, color="white")
plt.axis('off')
plt.xlim([0, 270])
plt.ylim([0, 270])
fig.subplots_adjust(
top=1.0,
bottom=0.0,
left=0.0,
right=1.0,
hspace=0.2,
wspace=0.2
)
plt.savefig('testplot.png')
plt.show()
The resulted image: