samuel fipps
samuel fipps

Reputation: 45

Matplotlib how to scale the x axis by a factor of 2

I'm trying to plot something in matplotlib and I want the x axis to have the values. 0 2 4 8 16 32 64 256

plt.xticks Doesn't work because it doesn't evenly scale the x axis. It does what is in the imagine below.

plt.xticks([0, 2, 4 ,8 ,16 ,32, 64, 128, 256])

enter image description here

Is there anyway to get the imagine to look like this imagine below?

enter image description here

Where the numbers are even spaced along the bottom like this?

Upvotes: 3

Views: 3242

Answers (2)

Samuel Fipps
Samuel Fipps

Reputation: 300

axis = fig.add_subplot()
ax.set_xscale("log")
ax.xaxis.set_ticklabels([0, 2, 4 ,8 ,16 ,32, 64, 128, 256])
ax.xaxis.set_ticks([0, 2, 4 ,8 ,16 ,32, 64, 128, 256])
    
ax.plot(x)
plt.show

Upvotes: 3

user18098820
user18098820

Reputation:

If you want matplotlib to space the values evenly and not according to the numerical values you need to give them as text and not as numbers.
The following code gives a straight line when x is given as text and a curve when x is given as numerical values.

import numpy as np
from matplotlib import pyplot as plt

# numerical values, spacing according to value, gives a curve
x = np.array([2,4,8,16,32,64,128,256]) 

# text values, spaced evenly, gives a straight line
x = np.array(['2','4','8','16','32','64','128','256'])

y = np.arange(1,9)
plt.title("Matplotlib demo")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.plot(x,y)
plt.show()

Upvotes: 0

Related Questions