Modifying Color of Matplotlib Plot through C Programming Language

Solution 1 allows you to plot lines, while color points can be achieved by using the argument. The output will be a graph with colored points. On the other hand, Solution 2 provides a code that colors points in a specific pattern of red, green, and blue, regardless of the values of x and y. To color the points in Solution 1, you can pass the argument and the desired colors will be produced. In Solution 2, you can refer to the documentation for the scatter function to understand how the “c” argument can be used to specify colors in different ways. Additionally, a picker can be created on the legend artist to keep track of the artist’s state, which is easier than using due to internal conversion of colors to RGB tuples.


The matplotlib documentation offers an illustration of how to pick a legend, which can be modified to suit the scenario where picking occurs on a scatter plot with a color change.

In order to differentiate between the two states of the legend artist (proxy), we have developed a picker and assigned an attribute called


. This approach is more convenient compared to using


since the colors are internally converted to RGB tuples.

import matplotlib.pyplot as plt
x1 = [1,3,5,7,9]
x2 = [2,4,6,8,10]
fig, ax = plt.subplots()
line1 = ax.scatter(x1,x1,color = 'b',s = 50,label = 'x1')
line2 = ax.scatter(x2,x2,color = 'b',s = 50,label = 'x2')
leg = ax.legend(loc = 'upper left')
# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
for legline, origline in zip(leg.legendHandles, lines):
    legline.set_picker(5)  # 5 pts tolerance
    legline.toggled = False  # create custom attribute to observe state
    lined[legline] = origline
def onpick(event):
    legline = event.artist
    origline = lined[legline]
    c = "b" if legline.toggled else "r"
    legline.toggled = not legline.toggled
fig.canvas.mpl_connect('pick_event', onpick)

Frequently Asked Questions