【问题标题】:ax.xaxis.set_major_formatter does not change the bumber of shown digits for Xtick labelsax.xaxis.set_major_formatter 不会更改 Xtick 标签的显示位数
【发布时间】:2018-01-07 15:36:50
【问题描述】:

我有一个熊猫数据框,我正在尝试绘制两列相互对比的图。但问题是我的 xtick 标签显示为完全精确。如何缩写(我的 Xaxis 值是元组)?

fig = plt.figure(figsize=(13,160))
plt.style.use('ggplot')
sns.set_style('ticks')
plt.rcParams['font.size'] = 12 
n = 0

for name, group in a.groupby(['Config','prot_state','repeat','leg']):
    ax = fig.add_subplot(20,2,n+1)
    group = group.sort_values(by='Lambda')

    title = name[0]+'-'+name[1]+'-'+name[2]+'('+name[3]+')'
    ax = group.plot(y='A', x='Lambda', ax=ax, marker='o', lw=3, label='Chain_A', title=title)
    ax = group.plot(y='B', x='Lambda', ax=ax, marker='o', lw=3, label='Chain_B', title=title)
    ax.set_xlabel('$\lambda_{Coul}$, $\lambda_{Vdw}$')
    ax.set_ylabel('$\Delta G$ (KJ/mol)')
    ax.get_xaxis().get_major_formatter()
    sns.despine(offset=10, ax=ax)
    labels = ax.get_xticklabels()
    plt.setp(labels, rotation=90, fontsize=10)
    ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    plt.xticks(range(len(group['Lambda'])), group['Lambda'])

    n = n+1 

fig = ax.get_figure()  
plt.tight_layout()
fig.savefig('{}.pdf'.format('dg-dlambda'))

有谁知道如何将其缩写为两位数?

【问题讨论】:

  • 显示的所有" 都是,这使您的代码难以重现,请记住始终建议提供问题的Minimal, Complete, and Verifiable example 并用它编辑您的问题。关于问题本身,只需致电 ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f')) 即可解决问题。
  • 我将 ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) 添加到我的代码中(见上文)。但它实际上什么也没做

标签: python pandas matplotlib


【解决方案1】:

如果您的ax.xaxis.set_major_formatter(FormatStrFormatter(‘%.1f’)) 不起作用,您可以先将它们转换为字符串(前提是它们都是相同的数量级)然后将它们切片来欺骗它:

labels = ax.get_xticklabels()
new_labels = []
n_digits = 2 + 1 # you will use this for slicing the string, so the +1 is there so that your last digit doesn't get excluded. The first number (2) is arbitrary, depending how many you want.
for i in labels:
    new_i = str(i)[:n_digits]
    new_labels.append(new_i)

plt.xticks(labels, new_labels)

但是,显然,这只有在它们的小数点前位数相同时才有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多