Reputation: 34715
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"
Upvotes: 6
Views: 12535
Reputation: 35463
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.
Upvotes: 4
Reputation: 4685
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. :-)
Upvotes: 9