Python 如何将绘图线颜色从蓝色更改为黑色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41709257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the plot line color from blue to black?
提问by sdg
I am stuck when I have generated a set of data and tried to color the plot line in python.
当我生成一组数据并尝试在 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()
回答by ImportanceOfBeingErnest
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.
在 matplotlib 中设置线条颜色的常用方法是在 plot 命令中指定它。这可以通过数据后的字符串来完成,例如"r-"
红线,或者通过明确说明color
参数。
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.
另请参阅plot 命令的文档。
In case you already have a line with a certain color, you can change that with the lines2D.set_color()
method.
如果您已经有一条带有某种颜色的线条,您可以使用该lines2D.set_color()
方法进行更改。
line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")
在 Pandas 图中设置线的颜色也最好在创建图时完成:
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.
如果您有更多行,您也可以循环遍历它们。