Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

How to always place axis unit in specific tick label position in Matplotlib?

$
0
0

There is a specific way of including units in graphs that I like:Image from wikipedia

The image is from Wikipedia, from a page about DIN 461.

The unit is always placed in the second to last axis tick. I want to recreate this kind of behaviour using Matplotlib and I have been successful by modifying the xlabels directly using plt.gca().set_xticklabels(). The use of set_xticklabels is however discouraged, because it stops displaying the proper values once you zoom/pan, do whatever with the plot. Instead, I would like to have a solution, where the second to last tick label is always changed to be a unit.

I tried writing a custom tick label formatter and placing the unit depending on the position. This has not yet worked, due to the different number of ticks that might be shown, depending on the zoom aspect ratio, etc., as well as the fact, that pos is often None, for some reason. Alternatively, I used ax.set_xticks with some formatting function Formatter: ax.set_xticks(ax.get_xticks(), Formatter(ax.get_xticks())), but this shows more ticks than I want and also does not change the ticks when zooming.

from matplotlib.ticker import FuncFormatter@FuncFormatterdef my_formatter(x, pos):    return f"{x}" if pos != 6 else 'Unit'

Is there a nice way of doing this?


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>