Home > Enterprise >  Linearly scale axes from kilometers to meters for all plots in matplotlib
Linearly scale axes from kilometers to meters for all plots in matplotlib

Time:12-22

I am working with data in meters and want to plot positions. Having the ticks in meters is obscuring the readability of the plots, so I want to plot the data in kilometers. I know that it is possible to scale all data d/1000., however, this makes the code less readable in my eyes, especially if you're plotting many different lines, where you have to do this transformation every time.

I am looking for a general way to achieve this type of transformation, I could imagine there is a beautiful way to achieve this in matplotlib.

Some sample code for you:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(7500, 30000, 300)
y_ref = np.linspace(5000, 15000, 300)
y_noised = y_ref   np.random.normal(0, 250, size=y_ref.size)

fig = plt.Figure(figsize=(6,6))
ax = fig.add_subplot(1, 1, 1)

ax.plot(x, y_ref, c='r')
ax.scatter(x, y_noised, alpha=0.2)
fig

Output figure

I would like to have the following figure, without needing to scale x, y_ref and y_noised individually by 1000.

Desired output

Is there a way to perform this transformation in matplotlib, such that you only need to do it for each figure once, no matter how many lines you plot?

CodePudding user response:

You could use a custom tick formatter like that (passing a function into enter image description here

  • Related