Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change subplot color in DataFrame?

I would like to change color of individual subplot:
1. Specifying desired color of plots by hand
2. Using random colors

Basic code (taken from 1)

 df = DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
 df = df.cumsum()

 df.plot(subplots=True)
 plt.legend(loc='best') 
 plt.show()

I tried this:

 colors = ['r','g','b','r']                   #first option
 colors = list(['r','g','b','r'])             #second option
 colors = plt.cm.Paired(np.linspace(0,1,4))   #third option

 df.plot(subplots=True, color=colors)

But all of them doesn' work. I found 2 but I'm not sure how to change this:

 plots=df.plot(subplots=True)
 for color in plots:
   ??????
like image 421
Michal Avatar asked Feb 15 '23 12:02

Michal


2 Answers

You can easlity do this by providing the style parameter with a list of color abbrevations:

from pandas import Series, DataFrame, date_range
import matplotlib.pyplot as plt
import numpy as np

ts = Series(np.random.randn(1000), index=date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

df = DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()

ax = df.plot(subplots=True, style=['r','g','b','r'], sharex=True)
plt.legend(loc='best')
plt.tight_layout()
plt.show()

enter image description here


Random colors from "standard" colors

If you only want to use the "standard" colors (blue, green, red, cyan, magenta, yellow, black, white), you can define an array containing the color abbrevations and pass a random sequence of these as argument to the style parameter:

colors = np.array(list('bgrcmykw'))

...

ax = df.plot(subplots=True,
             style=colors[np.random.randint(0, len(colors), df.shape[1])],
             sharex=True) 
like image 137
sodd Avatar answered Feb 18 '23 03:02

sodd


You'll have to loop over each axis by itself and do this manually as far as I can tell. This should probably be a feature.

df = DataFrame(np.random.randn(1000, 4), columns=list('ABCD'))
df = df.cumsum()
colors = 'r', 'g', 'b', 'k'
fig, axs = subplots(df.shape[1], 1,sharex=True, sharey=True)
for ax, color, (colname, col) in zip(axs.flat,colors,df.iteritems()):
    ax.plot(col.index,col,label=colname,c=color)
    ax.legend()
    ax.axis('tight')
fig.tight_layout()

enter image description here

Or if you have dates in your index do:

import pandas.util.testing as tm

df = tm.makeTimeDataFrame()
df = df.cumsum()
colors = 'r', 'g', 'b', 'k'
fig, axs = subplots(df.shape[1], 1,sharex=True, sharey=True)
for ax, color, (colname, col) in zip(axs.flat, colors, df.iteritems()):
    ax.plot(col.index, col, label=colname,c=color)
    ax.legend()
    ax.axis('tight')
fig.tight_layout()
fig.autofmt_xdate()

to get

enter image description here

like image 30
Phillip Cloud Avatar answered Feb 18 '23 03:02

Phillip Cloud