在Pandas.DataFrame.Plot中使用Colormap功能

2024-06-25 23:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

from matplotlib import cm
a = pd.DataFrame(zip(ranFor.feature_importances_, trainSet.columns))
a = a.sort_values(by = [0], ascending= False)
tinydata = a.iloc[:25]
tinydata = tinydata[::-1]
tinydata.set_index([1], inplace=True)
cmap = cm.get_cmap('jet')
colors = cm.jet(np.linspace(0,1,len(tinydata)))
tinydata.plot(kind = 'barh', figsize = (15,10), title = 'Most Important 20 Features of the Initial Model',
                    grid = True, legend = False, color = colors)
plt.xlabel('Feature Importance')
plt.show()

大家好,这是我绘制条形图的代码。问题是,我不知道如何用彩色贴图绘制颜色,透明度越来越高,就像我在问题中附加的图形一样。多谢各位

The graph I mentioned

编辑

colors = cm.Reds(np.linspace(0,len(tinydata),1))
tinydata.plot(kind = 'barh', figsize = (15,10), title = 'Most Important 20 Features of the Initial Model',
                    grid = True, legend = False, color = colors)

我做了一个这样的改变,我想它起作用了,但是颜色真的很淡。我怎样才能改变这个


Tags: falsetruelenplottitlenpcmcmap
1条回答
网友
1楼 · 发布于 2024-06-25 23:22:43

熊猫恐怕不提供这种功能。尽管他们说in the documentationcolor可以接受一个数组,但这指的是不同的列,我们在本例中也可以看到:

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

tinydata = pd.DataFrame({"ind": list("ABCDEF"), 
                         "X": [10, 8, 7, 6, 4, 1], 
                         "Y": [5,  3, 4, 2, 3, 1],
                         "Z": [8,  5, 9, 6, 7, 3] })
tinydata = tinydata[::-1].set_index("ind")
n = len(tinydata)
colors = cm.Reds(np.linspace(0.2, 0.8, 3))
tinydata.plot(kind = 'barh', figsize = (15,10), title = 'Most Important 20 Features of the Initial Model',
                    grid = True, legend = True, color = colors)
plt.xlabel('Feature Importance')
plt.show()

输出: ![enter image description here

在提供常用绘图功能的情况下,这是有意义的。因此,对于您的应用程序,它回到了pandas所依赖的matplotlib的多功能性:

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

tinydata = pd.DataFrame({"ind": list("ABCDEF"), 
                         "X": [10, 8, 7, 6, 4, 1]})
tinydata = tinydata[::-1].set_index("ind")
n = len(tinydata)
colors = cm.Reds(np.linspace(0, 1, n))

fig, ax = plt.subplots(figsize = (15,10))
ax.barh(tinydata.index, tinydata.X, color = colors)
ax.grid(True)
ax.set_xlabel('Feature Importance')
ax.set_title('Most Important 20 Features of the Initial Model',)
plt.show()

输出:enter image description here

相关问题 更多 >