Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 232
qznc Avatar asked Jun 09 '16 09:06

qznc


People also ask

How do you put a space between subplots in Python?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.

How do I show multiple plots in Matplotlib?

To draw multiple plots using the subplot() function from the pyplot module, you need to perform two steps: First, you need to call the subplot() function with three parameters: (1) the number of rows for your grid, (2) the number of columns for your grid, and (3) the location or axis for plotting.


1 Answers

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

like image 91
Serenity Avatar answered Oct 17 '22 23:10

Serenity