How to change color of particular edge for polygon in python?

主宰稳场 提交于 2020-02-06 07:45:05

问题


There is a polygon and I am wondering how can I change color of particular edge of it like figure below.

import matplotlib.pyplot as plt
import numpy as np


## -----------------------Initialize Geometry----------------------- 
pixels = 600
my_dpi = 100

coord = [[-150,-200],[300,-200],[300,0],[150,200],[-150,200]]


fig = plt.figure(figsize=( pixels/my_dpi,  pixels/my_dpi), dpi=my_dpi)  

plt.axes([0,0,1,1])

rectangle = plt.Rectangle((-300, -300), 600, 600, fc='k')
plt.gca().add_patch(rectangle)
polygon = plt.Polygon(coord,fc='w')
plt.gca().add_patch(polygon)
plt.axis('off')
plt.axis([-300,300,-300,300])

plt.savefig('figure1/5.jpg',dpi=my_dpi)

回答1:


The easiest way to do this would be to simply plot a line between the two relevant vertices of the polygon, i.e.

plt.plot([coords[0,0], coords[-1,0]], [coords[0,1], coords[-1,1]], color='r', lw=5)

Would give you

Although I recommend adding a border to the polygon with the same width as this line of the same color as the facecolor:

polygon = plt.Polygon(coord,fc='w',ec='w',lw=5)

As a way to make the red line appear flush. You can change which edge is colored you simply change the indices of coords[i,j] in plt.plot() and as long as the indices are adjacent (with wrapping - so last index and first index are adjacent) the line drawn will be an edge and not a diagonal.

Also note you can shorten the plotting command by using slices or a helper function but I have neglected this for the sake of being explicit.



来源:https://stackoverflow.com/questions/59915009/how-to-change-color-of-particular-edge-for-polygon-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!