9

I'm trying to use a matplotlib.colormap object in conjunction with the pandas.plot function:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm

df = pd.DataFrame({'days':[172, 200, 400, 600]})
cmap = cm.get_cmap('RdYlGn')
df['days'].plot(kind='barh', colormap=cmap)
plt.show()

I know that I'm supposed to somehow tell the colormap the range of values it's being fed, but I can't figure out how to do that when using the pandas .plot() function as this plot() does not accept the vmin/vmax parameters for instance.

1 Answer 1

9

Pandas applies a colormap for every row which means you get the same color for the one-column data frame.

To apply different colors to each row of your data frame you have to generate a list of colors from the selected colormap:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

df = pd.DataFrame({'days':[172, 200, 400, 600]})
colors = cm.RdYlGn(np.linspace(0,1,len(df)))
df['days'].plot(kind='barh', color=colors)
plt.show()

enter image description here

Another method is to use matplotlib directly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that helped! I ended up using colors = cm.RdYlGn(np.logspace(0,1,len(df))*df['days'].values/df['days'].max())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.