Felippe Trigueiro
Felippe Trigueiro

Reputation: 109

How do I change the scale distance in the Y axis using Matplotlib?

I'm trying to change the scale of the Y axis from 1 to millions, e.g., (0, 1000, 2000, 3000, ...) transforms in (0, 1, 2, 3, ...). I looked for in lots of matplotlib functions, but I did not find the answer. How can I do that?

Thanks.

Upvotes: 1

Views: 880

Answers (2)

errno98
errno98

Reputation: 332

Simplest way would be to modify the y-ticks, if you don't want to create new data. Example:

Original:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1e6 *  np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

plt.show()

enter image description here

And with modification for y-ticks:

t = np.arange(0.0, 2.0, 0.01)
s = 1e6 *  np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set_yticklabels([y/1e6 for y in ax.get_yticks()])  # divide every tick value by 1 million

plt.show()

enter image description here You could also specify x- or y-axis scale by using consequently plt.xscale or plt.yscale parameters along with custom matplotlib.scale.register_scale.

Upvotes: 1

Liam W
Liam W

Reputation: 11

You can simply to scale the data itself and label the axis accordingly:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x_data = [1, 2, 3, 4, 5]
y_data = [1e6, 2e6, 4e6, 8e6, 16e6]

scale_factor = 1e6
y_data_scaled = [y / scale_factor for y in y_data]

ax.plot(x_data, y_data_scaled)
ax.set_ylabel('My Data (Millions)')

Expected output plot

Upvotes: 1

Related Questions