0
votes

I have embedded a matplotlib figure in a PySide app. I'm trying to expose some of the functionality to the user (via gui buttons etc) to help them customise the figure.

I'm having trouble to get the x and y axis limits to update when told to. I have this function:

def set_xlimits(self, lower, upper):
    """ Convenience method to canvas.axes.set_xlim """
    self.canvas.axes.set_xlim(lower, upper)
    self.canvas.draw()

where axes is a matplotlib.axes.Axes instance and canvas is inherited from FigureCanvasQTAgg

When I call this method, with new limits, either nothing happens or new ticks are added to the axis, but no new tick labels (i.e. if changing from limits of 0,1 to 0,10, it will still remain labelled from 0-1, but with some extra ticks beyond 1)

Any ideas on how to always enforce the change?

Edit: It seems that the axes limits are updated, but the ticks are not. So, if I change the limits to 0-16, the ticks will still stay 0-1, but all data in the range 0-16 is displaedy ?!

When I subsequently call another method, such as this one to edit the tick label font:

def set_tick_font(self, font):
    self.canvas.axes.set_xticklabels(self.canvas.axes.get_xticks(), **font)
    self.canvas.axes.set_yticklabels(self.canvas.axes.get_yticks(), **font)
    self.canvas.draw()

The previous call to update the axis limits is finally drawn. This isnt ideal - it should have been drawn the first time. Any ideas what is going on?

1
do not use set_*ticklabels unless you are really sure what you are doing. It decouples your tick labels from your data is inherently dangerous. - tacaswell
despite being very vague, your are right. After investigating the mpl source code, using a combination of get_*ticklabels() and set_fontproperties allows the tick labels to be altered without decoupling from the data (and thus preventing the set_*lim method from correctly updating) - jramm

1 Answers

0
votes

As tcaswell hinted at, it seems my second method - to set the tick font, was somehow preventing the set_xlim and set_ylim methods from working correctly.

I still need to look at exactly how it works, but for now, changing the second method to:

def set_tick_font(self, font):
    fnt = font_manager.FontProperties(**font)
    for labelx, labely in zip(self.canvas.axes.get_xticklabels(), self.canvas.axes.get_yticklabels()):
        labelx.set_fontproperties(fnt)
        labely.set_fontproperties(fnt)
    self.canvas.draw()

means that the limits will now update correctly when calling the set_xlimits method and I can still independently change the tick label font.