Emmet B
Emmet B

Reputation: 5531

Matplotlib: Scale axis by multiplying with a constant

Is there a quick way to scale axis in matplotlib?

Say I want to plot

import matplotlib.pyplot as plt
c= [10,20 ,30 , 40]
plt.plot(c)

it will plot

enter image description here

How can I scale x-axis quickly, say multiplying every value with 5? One way is creating an array for x axis:

x = [i*5 for i in range(len(c))]
plt.plot(x,c)

enter image description here

I am wondering if there is a shorter way to do that, without creating a list for x axis, say something like plt.plot(index(c)*5, c)

Upvotes: 5

Views: 17591

Answers (2)

Ali_Sh
Ali_Sh

Reputation: 2816

It's been a long time since this question is asked, but as I searched for that, I write this answer. IIUC, you are seeking a way to just modify x ticks without changing the values of that axis. So, as the unutbu answer, in another way using arrays:

plt.plot(c)
plt.xticks(ticks=plt.xticks()[0][1:], labels=5 * np.array(plt.xticks()[0][1:], dtype=np.float64))
plt.show()

enter image description here

Upvotes: 1

DilithiumMatrix
DilithiumMatrix

Reputation: 18627

Use a numpy.array instead of a list,

c = np.array([10, 20, 30 ,40])   # or `c = np.arange(10, 50, 10)`
plt.plot(c)
x = 5*np.arange(c.size)  # same as `5*np.arange(len(c))`

This gives:

>>> print x
array([ 0,  5, 10, 15])

Upvotes: 1

Related Questions