代码之家  ›  专栏  ›  技术社区  ›  Chrisvdberge

Seaborn热图上y轴刻度的垂直对齐

  •  1
  • Chrisvdberge  · 技术社区  · 7 年前

    我在策划一场战争 Seaborn heatmap 我想把这个 y-axis 勾选标签,但找不到这样做的方法。 'va' yticks() .

    考虑到以下几点 形象

    enter image description here 我想把一周中的几天和一排正方形的中心对齐

    代码 要生成此图表:

    import pandas as pd
    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    
    #Generate dummy data
    startDate = '2017-11-25'
    dateList = pd.date_range(startDate, periods=365).tolist()
    df = pd.DataFrame({'Date': dateList,
                    'Distance': np.random.normal(loc=15, scale=15, size=(365,))
                  })
    #set week and day
    df['Week'] = [x.isocalendar()[1] for x in df['Date']]
    df['Day'] = [x.isocalendar()[2] for x in df['Date']]
    
    #create dataset for heatmap
    #group by axis to plot
    df = df.groupby(['Week','Day']).sum().reset_index()
    #restructure for heatmap
    data = df.pivot("Day","Week","Distance")
    
    #configure the heatmap plot
    sns.set()
    fig, ax = plt.subplots(figsize=(15,6))
    ax=sns.heatmap(data,xticklabels=1,ax = ax, robust=True, square=True,cmap='RdBu_r',cbar_kws={"shrink":.3, "label": "Distance (KM)"})
    ax.set_title('Running distance', fontsize=16, fontdict={})
    
    #configure the x and y ticks
    plt.xticks(fontsize="9")
    plt.yticks(np.arange(7),('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), rotation=0, fontsize="10", va="center")
    
    #set labelsize of the colorbar
    cbar = ax.collections[0].colorbar
    cbar.ax.tick_params(labelsize=10)
    
    plt.show()
    
    2 回复  |  直到 7 年前
        1
  •  15
  •   onno    7 年前

    添加 +0.5 np.arange(7) plt.yticks 为我工作

    plt.yticks(np.arange(7)+0.5,('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), rotation=0, fontsize="10", va="center")
    
        2
  •  7
  •   Shaido MadHadders    5 年前

    OnNO的解决方案适用于这种特殊情况(矩阵类型图通常在贴片的中间有标签),但也可以考虑这些更一般的方法来帮助您:

    a) 先找出蜱虫在哪里

    pos, textvals = plt.yticks()
    print(pos)
    
    >>> [0.5 1.5 2.5 3.5 4.5 5.5 6.5]
    

    plt.yticks(pos,('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), 
        rotation=0, fontsize="10", va="center")
    

    pyplot命令 xticks & yticks 同时更新位置和文本。但是axes对象有独立的位置方法( ax.set_yticks(pos) )对于文本( ax.set_yticklabels(labels)

    只要你知道要生产多少个标签(以及它们的顺序),你甚至不需要考虑它们的位置来更新文本。

    ax.set_yticklabels(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'), 
        rotation=0, fontsize="10", va="center")
    
        3
  •  1
  •   a11    5 年前

    g = sns.heatmap(df)
    g.set_yticklabels(labels=g.get_yticklabels(), va='center')
    

    当然你可以定义 labels=myLabelList