qznc qznc - 1 year ago 146
Python Question

Custom xticks for multiple subplots?

Using Matplotlib, I have two subplots and I want them to have the same custom string xticks.

Here is a minimal example what I tried so far:

import matplotlib.pyplot as plt
f, axs = plt.subplots(ncols=2, sharex=True)
plt.xticks(range(6), [str(x)+"foo" for x in range(6)], rotation='45')
for i in range(2):
ax = axs[i]
ax.plot(range(6), range(6))

Produces this output:

output of code example

Note that the xticks on the left are not rotated. How can I do that?

If I remove the
, the left subplot has no custom xticks. However, I cannot give xticks to a single axis. It results in an error:

AttributeError: 'AxesSubplot' object has no attribute 'xticks'


If sharex is not principal use this code:

import matplotlib.pyplot as plt
f, axs = plt.subplots(ncols=2)
for i in range(2):
    ax = axs[i]
    ax.set_xticklabels([str(x)+"foo" for x in range(6)], rotation=45)
    ax.plot(range(6), range(6))

enter image description here