简体   繁体   中英

Using Colormap feature with Pandas.DataFrame.Plot

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

Hello everyone, this is my code for plotting a bar plot. The problem is I couldn't figure out how to plot the colors with colormap with an increasing transparency like the graph I am attaching to my question. Thank you.

我提到的图表

EDIT

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)

I made a change like this and I guess it worked but the colors are really pale. How can I change this.

I am afraid that pandas does not provide this functionality. Although they say in the documentation that color can take an array, this refers to different columns, as we can also see in this example:

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

Output: ![在此处输入图像描述

In the context of pandas providing commonly used plotting functions, this makes sense. So, for your application, it is back to the multifunctionality of matplotlib on which pandas relies anyhow:

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

Output: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM