【问题标题】:Using Colormap feature with Pandas.DataFrame.Plot将 Colormap 功能与 Pandas.DataFrame.Plot 一起使用
【发布时间】:2021-04-04 16:39:50
【问题描述】:
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()

大家好,这是我绘制条形图的代码。问题是我无法弄清楚如何使用颜色图绘制颜色,并增加透明度,就像我附加到我的问题的图表一样。谢谢。

编辑

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)

我做了这样的改变,我想它有效,但颜色真的很苍白。我该如何改变这个。

【问题讨论】:

  • 在值方面是一样的,但是颜色模式和最大的列是一样的,我希望它随着值的变小而更加透明。

标签: python pandas dataframe matplotlib colormap


【解决方案1】:

恐怕熊猫不提供这个功能。虽然他们说in the documentation color 可以接受一个数组,但这指的是不同的列,我们也可以在这个例子中看到:

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

输出:

在 pandas 提供常用绘图功能的上下文中,这是有道理的。因此,对于您的应用程序,它又回到了 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()

输出:

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 2012-08-29
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多