Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I change line color after calling matplotlib plot?

The following code, take from thetechrepo tutorial, will plot some data with different colors.

import matplotlib.pyplot as plt
plt.figure()

#create data
x_series = [0,1,2,3,4,5]
y_series_1 = [x**2 for x in x_series]
y_series_2 = [x**3 for x in x_series]

plt.plot(x_series, y_series_1, 'r-')
plt.plot(x_series, y_series_2, 'c--')
plt.show()

However what if I wanted to change the colors after I've called plot? For example how would I change the color of series_1 to green after I had called plt.plot(x_series, y_series_1, 'r-')?

like image 843
rhody Avatar asked Mar 10 '16 20:03

rhody


People also ask

How do I change the color of a line in matplotlib?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

How do I change the marker color in matplotlib?

All of the line properties can be controlled by keyword arguments. For example, you can set the color, marker, linestyle, and markercolor with: plot(x, y, color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12).


1 Answers

you can use set_color on the Line2D object created by plt.plot. For example:

l1, = plt.plot(x_series, y_series_1, 'r-')
l2, = plt.plot(x_series, y_series_2, 'c--')

# Some time later...
l1.set_color('b')
l2.set_color('g')
like image 128
tmdavison Avatar answered Oct 15 '22 14:10

tmdavison