【问题标题】:Seaborn Align twinx and x AxisSeaborn 对齐 twinx 和 x 轴
【发布时间】:2022-10-07 20:41:22
【问题描述】:

我正在尝试将 X 轴与其双胞胎对齐,但我没有找到办法。

这是我的代码

# Initialize the figure
plt.figure(figsize=(16, 10))

# Adding a title
plt.title(f'Client Retention Quarters: Monthly Cohorts', fontsize = 14)

# Creating the heatmap
sns.heatmap(retention, annot = True,vmin = 0, vmax =30,cmap="flare", fmt='g')
plt.ylabel('Cohort Quarter')
plt.xlabel('')
plt.yticks( rotation='360')

#Twinx
ax2 = plt.twiny()
ax2.set_xticks(range(0,len(x2)))
ax2.set_xticklabels(labels=x2)
ax2.spines['top'].set_position(('axes', -0.10))
plt.show()

这是输出:

我想将百分比与 x 刻度对齐。

可能吗?

【问题讨论】:

    标签: python matplotlib seaborn x-axis


    【解决方案1】:

    您可以使用以下更新的代码。看看这是否有效。请注意,我对retentionx2 使用了随机数据。基本上,主要更改它以获得两个轴的xlim()s,然后调整它(参见 lambda f),使刻度对齐。最后使用 set_major_locator() 来修复这些点。希望这是您正在寻找的...

    retention = np.random.rand(10, 12) ##My random data
    # Initialize the figure
    plt.figure(figsize=(16, 10))
    
    # Adding a title
    plt.title(f'Client Retention Quarters: Monthly Cohorts', fontsize = 14)
    
    # Creating the heatmap
    ax=sns.heatmap(retention, annot = True,vmin = 0, vmax =30,cmap="flare", fmt='g') ## Note I am assigning to ax
    plt.ylabel('Cohort Quarter')
    plt.xlabel('')
    plt.yticks( rotation='360')
    
    x2 = np.around(np.linspace(1, 25, 12),2)
    #Twinx
    ax2 = ax.twiny()
    #ax2.set_xticks(range(0,len(x2))) ## Commented as not required
    #ax2.set_xticklabels(labels=x2) ## Commented as not required
    
    ## New code here ##
    import matplotlib.ticker
    l = ax.get_xlim()
    l2 = ax2.get_xlim()
    f = lambda y : l2[0]+(y-l[0])/(l[1]-l[0])*(l2[1]-l2[0]) ##Add delta to each tick
    ticks = f(ax.get_xticks())
    ax2.xaxis.set_major_locator(matplotlib.ticker.FixedLocator(ticks)) ##Set the ticks
    
    ax2.spines['top'].set_position(('axes', -0.10))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 2021-03-10
      • 2017-12-15
      • 2022-11-10
      • 2021-01-31
      • 2017-03-18
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多