5

I want to change the filled color in the stacked area plots drawn with Pandas.Dataframe.

import pandas as pd
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = df.plot.area(linewidth=0);

The area plot example

Now I guess that the instance return by the plot function offers the access to modifying the attributes like colors.

But the axes classes are too complicated to learn fast. And I failed to find similar questions in the Stack Overflow.

So can any master do me a favor?

L. Li
  • 113
  • 2
  • 7

3 Answers3

4

The trick is using the 'color' parameter:

Soln 1: dict
Simply pass a dict of {column name: color}

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'], )

ax = df.plot.area(color={'b':'0', 'c':'#17A589', 'a':'#9C640C', 'd':'#ECF0F1'})

Soln 2: sequence
Simply pass a sequence of color codes (it will match the order of your columns).

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'], )

ax = df.plot.area(color=('0', '#17A589', '#9C640C', '#ECF0F1'))

No need to set linewidth (it will automatically adjust colors). Also, this wouldn't mess with the legend.

3

Use 'colormap' (See the document for more details):

ax = df.plot.area(linewidth=0, colormap="Pastel1")

enter image description here

Lambda
  • 1,392
  • 1
  • 9
  • 11
0

The API of matplotlib is really complex, but here artist Module gives a very plain illustration. For the bar/barh plots, the attributes can be visited and modified by .patches, but for the area plot they need to be with .collections.

To achieve the specific modification, use codes like this.

import pandas as pd
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = df.plot.area(linewidth=0);

for collection in ax.collections:
    collection.set_facecolor('#888888')

highlight = 0
ax.collections[highlight].set_facecolor('#aa3333')

Other methods of the collections can be found by run

dir(ax.collections[highlight])
L. Li
  • 113
  • 2
  • 7