2

I have a panda data frame and I am trying to plot two columns vs each other. But the problem is that my xtick labels are being shown to the full precision. How can abbreviate that (My Xaxis values are tuple)?

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

Does anyone know how can I abbreviate this to two digits?

mahzadkh
  • 51
  • 6
  • 2
    All the `"` shown are `‘`, this makes hard to reproduce your code, remember it's always recommended to provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) of the issue and edit your question with it. About the issue itself, just calling `ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))` should do the trick. – Vinícius Figueiredo Jul 31 '17 at 23:12
  • 1
    Possible duplicate of [Matplotlib: Specify format of floats for tick lables](https://stackoverflow.com/questions/29188757/matplotlib-specify-format-of-floats-for-tick-lables) – Vinícius Figueiredo Jul 31 '17 at 23:12
  • I added ax.xaxis.set_major_formatter(FormatStrFormatter(‘%.1f’)) to my code (See above). But it actualy is not doing anything – mahzadkh Aug 01 '17 at 00:46

1 Answers1

1

If your ax.xaxis.set_major_formatter(FormatStrFormatter(‘%.1f’)) doesn't work, you can cheat it by first converting them to a string (provided they are all the same order of magnitude) and then slicing them:

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)

However, this will only work if they have the same number of digits before the decimal point, obviously.

durbachit
  • 4,626
  • 10
  • 36
  • 49