Home > OS >  Is there a possibility to manually distribute the position of the x-ticks along the x-axis in pyplot
Is there a possibility to manually distribute the position of the x-ticks along the x-axis in pyplot

Time:07-12

I have a simple scatter plot with two different y-axes, left (y1) and right (y2). I am plotting two values each, on two different categorical values on the x-axis (Cat1 and Cat2).

from matplotlib import pyplot as plt

x = ['Cat1', 'Cat2']
y1 = [12, 23]
y2 = [0.1, 0.06]

uplims_y1 = [2, 3]
lolims_y1 = [5, 1]

uplims_y2 = [0.01, 0.01]
lolims_y2 = [0.03, 0.02]

yerror_y1 = [lolims_y1, uplims_y1]
yerror_y2 = [lolims_y2, uplims_y2]

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# first plot
ax1.scatter(x, y1, color='b')
ax1.errorbar(x, y1, yerr=yerror_y1, capsize=10, ecolor='b', ls='none')

# second plot
ax2.scatter(x, y2, color='r' )
ax2.errorbar(x, y2, yerr=yerror_y2, capsize=10, ecolor='r', ls='none')

# naming the axes
ax1.set_ylabel('Y1', color='b')
ax2.set_ylabel('Y2', color='r')

plt.show()

This is the output I get:

enter image description here

How can I distribute the categorical variables along the x-axis to display the data points more centrally? Like pushing the Cat1-tick more to the right and Cat2-tick to the left.

CodePudding user response:

Just scale the x axis a bit wider, e.g.

ax1.set_xlim((-0.5, 1.5))

enter image description here

The categories are coded as 0 and 1, so the default x axis range is from -0.05 to 1.05 which squeezes the values a bit to the edges if there are just two categories.

  • Related