Home > database >  How to change the xticks in matplotlib
How to change the xticks in matplotlib

Time:09-28

I am trying to rename the yticks in matplotlib.
With this code lines I get the first figure.

from matplotlib import pyplot as plt
incr = -2
fig = plt.figure(figsize=(4,2))
ax = fig.add_subplot(111)
ax.set_yticks([])

yy = [[0.1, 0.2, 0.4], [0.2,0.3, 0.5], [0.4, 0.3, 0.5]]
for i in range(len(yy)):
    incr  = 2
    xx = list(range(len(yy[i])))
    xx = [x incr for x in xx]
    ax.plot(xx, yy[i])
    ax.plot([incr,incr], [0,.3])

Output fig.

How could I change the xticks as in this figure

Expected fig.

CodePudding user response:

from matplotlib import pyplot as plt

incr = -2
fig = plt.figure(figsize=(4,2))
ax = fig.add_subplot(111)
ax.set_yticks([])
xlabel = []
yy = [[0.1, 0.2, 0.4], [0.2,0.3, 0.5], [0.4, 0.3, 0.5]]
for i in range(len(yy)):
    incr  = 2
    xx = list(range(len(yy[i])))
    xx = [x incr for x in xx]
    ax.plot(xx, yy[i])
    ax.plot([incr,incr], [0,.3])
    xlabel.append(incr)

ax.set_xticks(xlabel)
ax.set_xticklabels(['set 1', 'set 2', 'set 3'], rotation=45)

for label in ax.get_xticklabels():
    label.set_horizontalalignment('left')

Output:

enter image description here

CodePudding user response:

One can also do this with pylab and xticks

import matplotlib
import matplotlib.pyplot as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()

https://matplotlib.org/stable/gallery/ticks_and_spines/ticklabels_rotation.html

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html

  • Related