X Tutup
Skip to content

matplotlib.ticker.FormatStrFormatter clashes with ax2.set_yticklabels when dual y-axis is used #7161

@FilipDominec

Description

@FilipDominec
  • Matplotlib version 1.5.1-1ubuntu1, Python version2.7.12, Platform Ubuntu 16.04 x64
  • I installed Matplotlib and Python from apt repository
  • Example:
#!/usr/bin/python3  
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig = matplotlib.pyplot.figure(figsize=(7,4), dpi=96, facecolor='#eeeeee', tight_layout=1)
ax = fig.add_subplot(111) 

x = np.arange(0., 10., 0.1)
ax.plot(x, 12+x**1.5+0.1*x**2.5)

## Simple axes
ax.set_xlabel('expected maximum load (kg)')
ax.set_ylabel('needed bar diameter (cm)')

ax2 = ax.twinx()
ax2.set_ylabel('bar cross-section (cm$^{2}$)')

## left and right y-axes apply to the same data, but the right one has a given functional dependency on the left one
## (in this example, right ticks share the position with the left ticks)
ylim2 = ax.get_ylim()
print(ax.get_ylim())
ax2.set_ylim(ax.get_ylim())
def tick_function(r): return r**2 + 0.123 # 10.46*(p**1.68)
ax2.set_yticks(ax.get_yticks()[:-1])
ax2.set_yticklabels(tick_function(ax.get_yticks()[:-1]))

## ERROR? When uncommented, the values on the secondary y-axis are not processed by tick_function!
ax2.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%.2g$\\pm \\beta$'))

## Finish the plot + save 
ax.set_title("with custom matplotlib.ticker.FormatStrFormatter")
ax.grid()
ax.legend(prop={'size':10}, loc='upper right')
fig.savefig('with_formatter_error.png')

In short, I define dual y-axes of a plot, and need the right y-axis to show some given function of the left one. But when I try to format the right axis using the FormatStrFormatter class, it takes the values which are not processed by my function.

I consider this to be a bug, preventing me from defining the values as 100.123+β, 400.123+β, 900.123+β ... on the right axis. None of the attached example figures is therefore acceptable.

Exchanging the order of the ax2.set_yticklabels and ax2.yaxis.set_major_formatter does not help. Switching to python2 does not help either. I did not test the latest git version yet.

without_formatter_correct
with_formatter_error

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup