Reputation: 235
Hey guys this is my first time posting here and hopefully this question isn't too trivial. I tried looking for a solution to this but couldn't find what I wanted.
I have this very simple code here which plots xy line graph
x = [1,2,3,10,11]
y = [1,2,3,4,5]
plt.plot(x,y)
plt.xticks(x)
The graph then looks like this: Graph
What I want to do is compress the x axis such that the spacing between each point is the same. E.g have the space between 3 to 10 be the same as the space between 1 to 2.
Is there a way to do this? Thanks!
Upvotes: 2
Views: 4114
Reputation: 9810
This should do it:
from matplotlib import pyplot as plt
fig,ax = plt.subplots()
x = [1,2,3,10,11]
y = [1,2,3,4,5]
ax.plot(y,marker='o')
ax.set_xticks([i for i in range(len(y))])
ax.set_xticklabels(x)
plt.show()
I added the markers to visualise the data points better. The result looks like this:
EDIT:
If you want to visualise that the axis is not continuous, you can find help in this answer.
EDIT2:
In my example, I only passed the y
-values to the plot
function, which means that the x
-values are implicitly calculated to be [1,2,3,4,5]. You can of course also pass the x
-values for each plot command explicitly and thereby variate at which x
-value which plot starts. For the example in your comment, this would be:
fig,ax = plt.subplots()
y1 = [1,2,3,4,5]
x1 = [i for i in range(len(y1))]
y2 = [2,3,4,5,6]
x2 = [i+1 for i in range(len(y2))]
xticks = list(set(x1+x2)) #or more explicit: [i for i in range(6)]
xtick_labels = [1,2,3,10,11,12]
ax.plot(x1,y1,marker='o')
ax.plot(x2,y2,marker='x')
ax.set_xticks(xticks)
ax.set_xticklabels(xtick_labels)
plt.show()
Upvotes: 2