Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the plot line color from blue to black?

I am stuck when I have generated a set of data and tried to color the plot line in python.

For example I would like to change the line color from blue to black here.

This is what I have and returns is the set of data that I got from pandas.

ax=plt.gca() ax.set_axis_bgcolor('#cccccc') returns.plot() 

Screenshot of plot

like image 909
sdg Avatar asked Jan 18 '17 00:01

sdg


People also ask

How do I change the line color in a plot?

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. See also the plot command's documentation.

How do I make Matplotlib black?

@alexzander If you want a black background for the axes, set 'axes. facecolor' to black.


1 Answers

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.

import matplotlib.pyplot as plt  plt.plot([1,2,3], [2,3,1], "r-") # red line plt.plot([1,2,3], [5,5,3], color="blue") # blue line  plt.show() 

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue") line.set_color("black") 


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:
import matplotlib.pyplot as plt import pandas as pd  df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]}) df.plot("x", "y", color="r") #plot red line  plt.show() 

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black") 

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:     ax.get_lines()[0].set_color("black") 

and if you have more lines you can loop over them as well.

like image 159
ImportanceOfBeingErnest Avatar answered Sep 23 '22 13:09

ImportanceOfBeingErnest