Search code examples
pythonmatplotlibpositionxvaluexticks

Positioning of y values in Matplotlib - Matplotlib values don't follow tick positioning


I tried to find a solution but unfortunately nothing worked till now.

I have this code example where the values are really close to the y axis on both sides and I would like to move them somewhat more to the center. Both ticks are supposed to be a comparison with each other.

from matplotlib import pyplot as plt

y = {}
x = ["a170", "b300"]
y["OlC"] = [1,2]
y["CSD"] = [3,4]
col=["b", "r"]
mark=[".","*"]
Fig, axs = plt.subplots(figsize=(3.25,3.25))
for i, meth in enumerate(y):
    axs.plot(x, y[meth], color = col[i], marker = mark[i], linestyle='None', label=meth) 

I tried to move the y ticks with the following code, but it did only move the ticks.

axs.set_xticks([0.25,0.75])

Is there any way to do move the values e.g. one on 25 % from left and the other one 75 % too, same as the ticks?

Thank you!

enter image description here


Solution

  • You can first plot using numbers on the x-axis and then set the limits, set the desired ticks and finally the ticklabels. You can choose your own favorite values in axs.set_xlim(-1, 2) depending on how close or far you want the ticks to be.

    for i, meth in enumerate(y):
        axs.plot(range(len(x)), y[meth], color = col[i], marker = mark[i], linestyle='None', label=meth) 
    
    axs.set_xlim(-1, 2)
    axs.set_xticks([0, 1])
    axs.set_xticklabels(x)
    axs.legend()
    

    enter image description here