【问题标题】:Access and change characteristics of a single line within pandas plot访问和更改熊猫图中单行的特征
【发布时间】:2016-03-12 04:42:53
【问题描述】:

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

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

产生这样的东西:

一个事后如何改变只有一行的样式,例如改变它的颜色、线宽和不透明度等?

【问题讨论】:

    标签: python pandas matplotlib plot dataframe


    【解决方案1】:

    正如@StefanJansen 所述,您可以通过从给定的Axes 访问lines 来编辑行的color

    你也可以像这样修改其他属性:

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

    要更改曲线下的面积,您需要访问存储在Axes 中的collections。这里有用的属性是coloralpha

    ax.collections[0].set_color('yellow')
    ax.collections[0].set_alpha(0.3)
    

    显然,您可以更改这些示例中的索引0 以修改其他lines/collections

    【讨论】:

    • 太好了,感谢@tom 的回答。非常有帮助。添加以下代码可以解决所有问题: ax = df.plot(kind='area',stacked=False) ax.lines[0].set_color('yellow') ax.collections[0].set_color('yellow' ),但是当我想用 ax.legend() 更新图例时,它现在看起来不同了,好像所有的线都只是线而不是区域。有什么提示吗?
    【解决方案2】:

    如果您像这样捕获pandas.plot() 返回的axes

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

    然后您可以访问lines 之类的属性并设置colors 之类的参数(matplotlib 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)
    

    【讨论】:

    • 这行得很好。是否也有类似的方法来操作相应行下的相应区域?
    • 您也可以使用fill_between,如下所示:telliott99.blogspot.com/2010/02/…
    • @iMo51:是的,从Axes 访问collections。有关示例,请参阅我的答案
    猜你喜欢
    • 2017-06-24
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2018-09-27
    • 2017-01-10
    相关资源
    最近更新 更多