xticks only applying to 1 graph

Viewed 30

I'm trying to change the x axis for my graphs but it's only going through for one of them. My other graph has not changed at all. Here is the code:

fig, (gr0, gr1) = plt.subplots(ncols=2, constrained_layout=True, figsize = (17,7))

#gr0 
gr0.plot(data['g1'])
gr0.set_title('text 1')

#gr1
gr1.plot(data['g2'])
gr1.set_title('text 2')

plt.xticks(fontsize=8, rotation=45)

plt.show()

Graphs when the code is ran: enter image description here

As you can tell by the picture, only the graph on the right has the x-axis updated to where the text is rotated and clearly visible. The other one is still the same :(

2 Answers

The

plt.xticks(..., rotation=45)

call might feel like it applies to the whole figure, when it's phrased that way. But behind the scenes it's really making a gca() call and manipulating that, which of course is gr1 at that point.

You could make a pair of xticks calls, much as you're already doing for title. But the fact that you asked about this plot's behavior on SO indicates that the way it's phrased is not a good match for clearly communicating the intent. So let's re-phrase it slightly, avoiding that global.

labels = [
    '2022-05-21',
    '2022-05-25',
    '2022-05-29',
]
gr0.set_xticks(labels=labels, rotation=45)
gr1.set_xticks(labels=labels, rotation=45)

Or consider moving to import seaborn. In which case the idiom would be the somewhat simpler

gr0.grid.set_xticklabels(rotation=45)
gr1.grid.set_xticklabels(rotation=45)

You can set it per axis using ax.tick_params(labelsize=8, labelrotation=45).

ig, (gr0,gr1) = plt.subplots(ncols=2, constrained_layout=True, figsize = (17,7))

#gr0 
gr0.plot(data['g1'])
gr0.set_title('text 1')
gr0.tick_params(labelsize=8, labelrotation=45)

#gr1
gr1.plot(data['g2'])
gr1.set_title('text 2')
gr1.tick_params(labelsize=8, labelrotation=45)

plt.show()

enter image description here

Related