gpt4 book ai didi

python - ax.xaxis.set_major_formatter 不会更改 Xtick 标签显示数字的数量

转载 作者:太空宇宙 更新时间:2023-11-04 05:02:19 24 4
gpt4 key购买 nike

我有一个 Pandas 数据框,我正在尝试绘制两列的对比图。但问题是我的 xtick 标签显示得很精确。如何缩写(我的 X 轴值是元组)?

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

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

最佳答案

如果您的 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)

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

关于python - ax.xaxis.set_major_formatter 不会更改 Xtick 标签显示数字的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45426471/

24 4 0