How to assign equal scaling along the x axis in Matplotlib?

I currently have:

x = [3.0, 4.0, 5.0, 5.0, 6.0, 7.0, 9.0, 9.0, 9.0, 11.0] y = [6.0, 5.0, 4.0, 2.5, 3.0, 2.0, 1.0, 2.0, 2.5, 2.5] 

Which gives the following graph:

enter image description here

I would like to have equal scaling on my axis. Therefore, instead of having such a large gap between 7 and 9, as well as 9 and 11, it will be a space equal to all the others. It looks like this:

enter image description here

To exclude 8 and 10 from the chart, I used ticks. Here is the relevant code:

 ax=fig.add_subplot(111, ylabel="speed") ax.plot(x, y, 'bo') ax.set_xticks(x) 

None of the examples on the matplotlib page have anything that I want. I was looking through the documentation, but all the β€œscaling” is due to what I don't want to do.

Can this be done?

+6
source share
1 answer

In addition to my comments on OP, you can build a graph with natural numbers from 1 to n, where n is the number of unqiue abscissa values ​​in your dataset. Then you can set x ticklabels for these unique values. The only problem I encountered while implementing this is handling duplicate abscissa values. To try to save this general, I came up with the following

 from collections import Counter # Requires Python > 2.7 # Test abscissa values x = [3.0, 4.0, 5.0, 5.0, 6.0, 7.0, 9.0, 9.0, 9.0, 11.0] # Count of the number of occurances of each unique `x` value xcount = Counter(x) # Generate a list of unique x values in the range [0..len(set(x))] nonRepetitive_x = list(set(x)) #making a set eliminates duplicates nonRepetitive_x.sort() #sets aren't ordered, so a sort must be made x_normalised = [_ for i, xx in enumerate(set(nonRepetitive_x)) for _ in xcount[xx]*[i]] 

At this point, we get print x_normalised give

 [0, 1, 2, 2, 3, 4, 5, 5, 5, 6] 

So, build y against x_normalised with

 from matplotlib.figure import Figure fig=Figure() ax=fig.add_subplot(111) y = [6.0, 5.0, 4.0, 2.5, 3.0, 2.0, 1.0, 2.0, 2.5, 2.5] ax.plot(x_normalised, y, 'bo') 

gives

Result of solution presented as plotted using matplotlib

Finally, we can change the label labels on the x-axis to reflect the actual values ​​of our original x-data using set_xticklabels using

 ax.set_xticklabels(nonRepetitive_x) 

Change To get the final graph, similar to the desired output in OP, you can use

 x1,x2,y1,y2 = ax.axis() x1 = min(x_normalised) - 1 x2 = max(x_normalised) + 1 ax.axis((x1,x2,(y1-1),(y2+1))) #If the above is done, then before set_xticklabels, #one has to add a first and last value. eg: nonRepetitive_x.insert(0,x[0]-1) #for the first tick on the left of the graph nonRepetitive_x.append(x[-1]+1) #for the last tick on the right of the graph 
+4
source

Source: https://habr.com/ru/post/923326/


All Articles