使用matplotlib colormap和pandas dataframe.plot函数 [英] using matplotlib colormap with pandas dataframe.plot function
问题描述
我正在尝试将matplotlib.colormap对象与pandas.plot函数结合使用:
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()
我知道我应该以某种方式告诉色图它正在馈入的值的范围,但是当使用pandas .plot()函数时我不知道该怎么做,因为此plot()不会接受例如vmin/vmax参数.
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.
推荐答案
Pandas为每一行应用一个颜色图,这意味着您为单列数据框获得相同的颜色.
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()
另一种方法是直接使用matplotlib.
Another method is to use matplotlib directly.
这篇关于使用matplotlib colormap和pandas dataframe.plot函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!