using matplotlib colormap with pandas dataframe.pl

2019-06-17 17:25发布

问题:

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:

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

Another method is to use matplotlib directly.