这道题给出了对y轴进行排序的解决方案:Data order in seaborn heatmap from pivot 但是如何对 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()
[输出]:
如果我需要对 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()
关于python - 如何对热图的索引 DataFrame 上的 x 轴和 y 轴执行自定义排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641618/