Line Segments in Matplotlib

久未见 提交于 2019-12-21 13:42:10

问题


Given coordinates of [1,5,7,3,5,10,3,6,8] for matplotlib.pyplot, how do I highlight or colour different segments of the line. For instance, the coordinates 1-3 ([1,5,7,3]) in the list represent attribute a. How do I colour this bit of the line and mark it in the legend?

Edit: The list in question contains tens of thousands of elements. I'm trying to highlights specific sections of the list. From the answers so far, is it right to assume I must draw each segment one by one? There isn't a way to say "select line segment from x1 coord to x2 coord, change colour of line"


回答1:


Yes, you need to redraw the line, but you can clip the line so that only the part you are interested in is visible. To do this I create a rectangle covering the area that represents prop (a), then I use this to create a clip_path.

import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

data = [1,5,7,3,5,10,3,6,8]
X0 = 1
X1 = 3

plt.plot(data, label='full results')
# make a rectangle that will be used to crop out everything not prop (a)
# make sure to use data 'units', so set the transform to transData
propArect = plt.Rectangle((X0, min(data)), X1, max(data), 
                          transform=plt.gca().transData)
# save the line so when can set the clip
line, = plt.plot(data,
         color='yellow',
         linewidth=8,
         alpha=0.5,
         label='Prop (a)',
         )
line.set_clip_path(propArect)

handles, labels = plt.gca().get_legend_handles_labels()
plt.legend(handles, labels)
plt.savefig('highlight.png')
plt.show()

This results in:

When I plotted the line segment, I adjusted the transparent-ness using the alpha keyword, which ranges from 0-1 or transparent to solid. I also made it a thicker line to extend beyond the original results.




回答2:


Try this on for size:

from matplotlib import pyplot as plt
y1 = [1,5,7,3]
x1 = range(1,5)
y2 = [3,5,10,3,6,8]
x2 = range(4,len(y2)+4)
plt.plot(x1, y1, 'go-', label='line 1', linewidth=2)
plt.plot(x2, y2, 'rs--',  label='line 2')
plt.legend()
plt.show()

Will give you:

Also, you ought to look at the help too, it's pretty helpful. :-)



来源:https://stackoverflow.com/questions/9434461/line-segments-in-matplotlib

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