multicolor points in one legend entry python

Solutions on MaxInterview for multicolor points in one legend entry python by the best coders in the world

showing results for - "multicolor points in one legend entry python"
Ariadna
04 Jun 2018
1import numpy as np
2import matplotlib.pyplot as plt
3from matplotlib.legend_handler import HandlerLineCollection
4from matplotlib.collections import LineCollection
5
6class HandlerColorLineCollection(HandlerLineCollection):
7    def create_artists(self, legend, artist ,xdescent, ydescent,
8                        width, height, fontsize,trans):
9        x = np.linspace(0,width,self.get_numpoints(legend)+1)
10        y = np.zeros(self.get_numpoints(legend)+1)+height/2.-ydescent
11        points = np.array([x, y]).T.reshape(-1, 1, 2)
12        segments = np.concatenate([points[:-1], points[1:]], axis=1)
13        lc = LineCollection(segments, cmap=artist.cmap,
14                     transform=trans)
15        lc.set_array(x)
16        lc.set_linewidth(artist.get_linewidth())
17        return [lc]
18
19t = np.linspace(0, 10, 200)
20x = np.cos(np.pi * t)
21y = np.sin(t)
22points = np.array([x, y]).T.reshape(-1, 1, 2)
23segments = np.concatenate([points[:-1], points[1:]], axis=1)
24
25lc = LineCollection(segments, cmap=plt.get_cmap('copper'),
26                    norm=plt.Normalize(0, 10), linewidth=3)
27lc.set_array(t)
28
29fig, ax = plt.subplots()
30ax.add_collection(lc)
31
32plt.legend([lc], ["test"],\
33    handler_map={lc: HandlerColorLineCollection(numpoints=4)}, framealpha=1)
34
35ax.autoscale_view()
36plt.show()
37
similar questions