I plot a line without specifying the color (think: plt.plot(x,y)). Say the color comes out blue.
Question: How do I obtain this color from the plt object so that I can put it into a variable?
Seems like this is close (and potentially the solution):
p = plt.plot(x,y) color = p[0].get_color()
Updated question: I am not sure I understand the "0" index: Does p[0] always access the most recent plotted line?
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.
The clf() function in pyplot module of matplotlib library is used to clear the current figure. Syntax: matplotlib.pyplot.clf()
You can adjust the colors of the points in a scatter plot using color maps (cmap argument), which allows you to specify a range of colors that will be applied to the data points depending on their value.
In your example, p is a list of Line2D object. In that example you have only one line object, p [0]. The following is an example plotting three lines. As more line is added, it is appended to the p. So if you want the color of the last plot, it will be p [-1].get_color ().
There are many ways by which you can change line color in matplotlib python. First, make sure that matplotlib is installed. The keyword arguments ( **kwargs) are used to change the colors. First import the matplotlib library. Using the plt.plot method type the points or lines that you want to plot.
For regular plt.plot, doing item.get_color () on each element of the list it returns will get you the colors of each line. But other plot functions, like plt.scatter, will return a Collection. For a Collection, you can call result.get_facecolor ().
Using the plt.plot method type the points or lines that you want to plot. In the brackets, if you don’t mention the line color as shown above; by default, it chooses the blue color.
In your example, p
is a list of Line2D
object. In that example you have only one line object, p[0]
. The following is an example plotting three lines. As more line is added, it is appended to the p
. So if you want the color of the last plot, it will be p[-1].get_color()
.
import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = np.arange(10) p = plt.plot(x,y, x,y*2, x,y*3) # make three line plots type(p) # list type(p[0]) # <class 'matplotlib.lines.Line2D'> p[0].get_color() # 'b' p[1].get_color() # 'g' p[2].get_color() # 'r'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With