【问题标题】:How to perform custom sort for both x- and y-axes on indexed DataFrame for heatmap?如何对热图的索引 DataFrame 上的 x 轴和 y 轴执行自定义排序?
【发布时间】:2018-03-20 09:04:20
【问题描述】:

这个问题给出了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-axis 显示顺序tv, phone(不只是颠倒顺序)

【问题讨论】:

    标签: python pandas pivot seaborn categorical-data


    【解决方案1】:

    我觉得你可以用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
    

    ordered categorical:

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

    【讨论】:

    • 很好的答案!你救了我的命!
    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多