如何将绘图线颜色从蓝色更改为黑色? [英] How to change the plot line color from blue to black?

查看:100
本文介绍了如何将绘图线颜色从蓝色更改为黑色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我生成一组数据并尝试在 python 中为绘图线着色时,我被卡住了.

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()

推荐答案

在 matplotlib 中设置线条颜色的常用方法是在 plot 命令中指定它.这可以通过数据后的字符串来完成,例如"r-" 表示红线,或者明确说明 color 参数.

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()

另请参阅绘图命令的文档.

如果您已经有一条带有某种颜色的线条,您可以使用 lines2D.set_color() 方法更改它.

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")

<小时>在 Pandas 图中设置线的颜色也最好在创建图时完成:


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.

这篇关于如何将绘图线颜色从蓝色更改为黑色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆