访问和更改pandas图中单行的特征

时间:2015-12-07 14:29:18

标签: python pandas matplotlib plot dataframe

使用pandas数据帧的内置功能进行绘图,例如一个未堆积的区域图如下:

df = pd.DataFrame(np.random.randn(11, 3)+3, columns=['r', 'g', 'b'])
df.plot(kind='area', stacked=False, alpha=0.75)

产生这样的东西:

一个事后如何改变一个单独行的风格,例如改变它的颜色,线宽和不透明度等等?

2 个答案:

答案 0 :(得分:4)

正如@StefanJansen所说,你可以编辑一行' color访问来自给定lines的{​​{1}}。

您还可以修改其他属性,如下所示:

Axes

要更改曲线下方的区域,您需要访问ax.lines[0].set_linewidth(2) # set linewidth to 2 ax.lines[0].set_linestyle('dashed') # other options: 'solid', 'dashdot` or `dotted` ax.lines[0].set_alpha(0.5) # Change the transparency ax.lines[0].set_marker('o') # Add a circle marker at each data point ax.lines[0].set_markersize(2) # change the marker size. an alias is set_ms() ax.lines[0].set_markerfacecolor # or set_mfc() ax.lines[0].set_markeredgecolor # or set_mec() 中存储的collections。这里有用的属性是Axescolor

alpha

显然,您可以更改这些示例中的索引ax.collections[0].set_color('yellow') ax.collections[0].set_alpha(0.3) 以修改其他0 / lines

答案 1 :(得分:1)

如果您捕获axes返回的pandas.plot(),请执行以下操作:

ax = df.plot(kind='area', stacked=False, alpha=0.75)

然后,您可以访问lines等属性,并设置colorsmatplotlib docs on axis API等参数以获取有关可用参数的详细信息):

ax.lines[0].set_color('red')

对于您的扩展问题,可以通过collections API修改该区域,如下所示:

ax.collections[0].set_color('color_name')

更改linescollections的索引可以更新特定项目。由于这些是可迭代的,您还可以迭代linescollections并执行以下操作:

for line in ax.lines:
    line.set_kwarg(foo)