【问题标题】:thick offset problem with matplotlib imshowmatplotlib imshow 的厚偏移问题
【发布时间】:2021-10-20 18:08:02
【问题描述】:

我正在尝试使用 matplotlib imshow 绘制相关矩阵。

这几乎是成功的,但我的滴答声偏移了,第一个不见了!?

这是我的代码:

fig1, ax = plt.subplots(1,1)
heatplot = ax.imshow(X.corr(), cmap='jet')
ax.set_xticklabels(X.columns)
ax.set_yticklabels(X.columns)
tick_spacing = 1
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))

结果:Tmin 应该超过 Tmax 但现在在最后一行没有打勾

【问题讨论】:

    标签: matplotlib imshow ticker


    【解决方案1】:

    调用ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) 不会指定起始刻度位置。显然,这里 matplotlib 还在位置 -1 处设置了一个刻度。此外,在调用set_xticklabels 之前,应固定刻度位置。

    最简单的方法是调用ax.set_xticks(range(len(X.columns))) 来指定所需的确切刻度。

    from matplotlib import pyplot as plt
    import numpy as np
    import pandas as pd
    
    fig1, ax = plt.subplots(1, 1)
    X = pd.DataFrame(np.random.rand(4, 10), columns=[*'abcdefghij'])
    heatplot = ax.imshow(X.corr(), cmap='seismic_r', vmin=-1, vmax=1)
    ax.set_xticks(range(len(X.columns)))
    ax.set_yticks(range(len(X.columns)))
    ax.set_xticklabels(X.columns, rotation=90)
    ax.set_yticklabels(X.columns)
    plt.show()
    

    seaborn 提供了一个更简单的接口,它可以自动完成很多事情:

    from matplotlib import pyplot as plt
    import seaborn as sns
    import numpy as np
    import pandas as pd
    
    X = pd.DataFrame(np.random.rand(4, 12), columns=['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'])
    sns.heatmap(data=X.corr(), cmap='RdYlGn', vmin=-1, vmax=1, annot=True)
    plt.xticks(rotation=30)
    plt.yticks(rotation=0)
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 它工作正常,非常感谢!
    猜你喜欢
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2020-07-08
    相关资源
    最近更新 更多