qznc qznc - 5 months ago 42
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))
f.show()


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
sharex=True
, 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'

Answer

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_xticks(range(6))
    ax.set_xticklabels([str(x)+"foo" for x in range(6)], rotation=45)
    ax.plot(range(6), range(6))
plt.show()

enter image description here