如何在python中更改多边形的特定边缘的颜色? [英] How to change color of particular edge for polygon in python?

查看:436
本文介绍了如何在python中更改多边形的特定边缘的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个多边形,我想知道如何更改其特定边缘的颜色,如下图所示.

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)

推荐答案

最简单的方法是在多边形的两个相关顶点之间绘制一条线,即

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)

会给你

尽管我建议向多边形添加边框,该边框的宽度与这条线的宽度相同,且颜色与facecolor相同:

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)

作为使红线显得平齐的一种方法.您可以更改哪个边缘是彩色的,只需更改plt.plot()中的coords[i,j]的索引,并且只要索引是相邻的即可(包绕-因此最后一个索引和第一个索引是相邻的),绘制的线条将是一条边缘而不对角线.

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.

这篇关于如何在python中更改多边形的特定边缘的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆