如何对索引DataFrame上的x轴和y轴执行自定义排序以获取热图?
问题描述:
这个问题给出了排序y轴的解决方案:Data order in seaborn heatmap from pivot 但是如何对x轴和y轴执行自定义排序?如何对索引DataFrame上的x轴和y轴执行自定义排序以获取热图?
没有自定义排序,我们看到订单:
- x轴:电话,电视
- y轴:苹果,谷歌,三星
代码:
lol = [['apple', 'phone', 10], ['samsung', 'tv', 20], ['apple', 'tv', 5], ['google', 'tv', 8], ['google', 'phone', 9], ['samsung', 'phone', 3]]
df = pd.DataFrame(lol)
df = df.rename(columns={0:'brand', 1:'product', 2:'count'})
df = df.pivot('brand', 'product', 'count')
ax = sns.heatmap(df)
plt.show()
[OUT]:
如果我需要排序的y轴显示的顺序samsung, apple, google
,我可以这样做:
lol = [['apple', 'phone', 10], ['samsung', 'tv', 20], ['apple', 'tv', 5], ['google', 'tv', 8], ['google', 'phone', 9], ['samsung', 'phone', 3]]
df = pd.DataFrame(lol)
df = df.rename(columns={0:'brand', 1:'product', 2:'count'})
df = df.pivot('brand', 'product', 'count')
df.index = pd.CategoricalIndex(df.index, categories= ["samsung", "apple", "google"])
df.sortlevel(level=0, inplace=True)
ax = sns.heatmap(df)
plt.show()
[出]:
但是如何对x轴和y轴执行自定义排序?,例如
-
y轴显示顺序
samsung, apple, google
-
x轴显示顺序
tv, phone
(不只是颠倒顺序)
答
我认为你可以使用reindex
:
a = ['samsung', 'apple', 'google']
b = ['tv','phone']
df = df.pivot('brand', 'product', 'count')
df = df.reindex(index=a, columns=b)
print (df)
product tv phone
brand
samsung 20 3
apple 5 10
google 8 9
df['brand'] = df['brand'].astype('category', categories=a, ordered=True)
df['product'] = df['product'].astype('category', categories=b, ordered=True)
df = df.pivot('brand', 'product', 'count')
print (df)
product tv phone
brand
samsung 20 3
apple 5 10
google 8 9
ax = sns.heatmap(df)
plt.show()