0

I have a plot where I need to specify some ticks but they are overlapping. An easy way to solve my problem would be by adding spaces at the end of the string defining my new ticks_label. However, it seems that all spaces are ignored...

In the following code an illustration with what I tried but doesn't work.

Any Idea ?

####### Solution Below #######

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

rc_fonts = {
   'text.usetex': True,
   'font.size': 20,
   'font.family': 'serif',
   'font.serif': 'cm'
}
mpl.rcParams.update(rc_fonts)

x = np.linspace(0, 1, 100, endpoint=True)
y = x**2

labels = ['0',r'$\varepsilon$', '1']
tested_labels1 = ['0',r'$\varepsilon$   ', '1']
tested_labels2 = ['0',r'$\varepsilon$\ \ \ \qquad', '1']
tested_labels3 = ['0',r'$\varepsilon\qquad$   ', '1']
x_labels = [0, 0.03, 1]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_yticks(x_labels, labels)
# Not Working the way I want => spaces are ignored
#ax.set_yticks(x_labels, tested_labels1)
#ax.set_yticks(x_labels, tested_labels2)
#ax.set_yticks(x_labels, tested_labels3)

plt.show()

enter image description here

####### Solution:

Thanks to Matt Pitkin I found a way. Clearly not as easy as just adding spaces, but working. Here the answer:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

rc_fonts = {
    'text.usetex': True,
    'font.size': 20,
    'font.family': 'serif',
    'font.serif': 'cm'
}
mpl.rcParams.update(rc_fonts)

x = np.linspace(0, 1, 100, endpoint=True)
y = x**2

labels = ['0',r'$\varepsilon$', '1']
x_labels = [0, 0.03, 1]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_yticks(x_labels, labels)

dx = -0.15; dy = 0. 
offset = mpl.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
ax.yaxis.get_majorticklabels()[1].set_transform(ax.yaxis.get_majorticklabels()[1].get_transform() + offset)

plt.show()

enter image description here

Hedwin
  • 31
  • 1
  • 6

1 Answers1

1

Thanks to Matt Pitkin I found a way. Clearly not as easy as just adding spaces, but working. Here the answer:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

rc_fonts = {
    'text.usetex': True,
    'font.size': 20,
    'font.family': 'serif',
    'font.serif': 'cm'
}
mpl.rcParams.update(rc_fonts)

x = np.linspace(0, 1, 100, endpoint=True)
y = x**2

labels = ['0',r'$\varepsilon$', '1']
x_labels = [0, 0.03, 1]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_yticks(x_labels, labels)

dx = -0.15; dy = 0. 
offset = mpl.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
ax.yaxis.get_majorticklabels()[1].set_transform(ax.yaxis.get_majorticklabels()[1].get_transform() + offset)

plt.show()

enter image description here

Hedwin
  • 31
  • 1
  • 6