Matplotlib show x axis values as integers on all subplots

Question:

import pandas as pd
import matplotlib.pyplot as plt

#...read data

fig, axes = plt.subplots(nrows=2, ncols=3)

df['Col1'].plot(ax=axes[0,0], title='Col1')
df['Col2'].plot(ax=axes[0,1], title='Col2')
df['Col3'].plot(ax=axes[0,2], title='Col3')
df['Col4'].plot(ax=axes[1,0], title='Col4')
df['Col5'].plot(ax=axes[1,1], title='Col5')
df['Col6'].plot(ax=axes[1,2], title='Col6')
plt.xticks(df['ID'])

plt.show()

No matter what I try, it only applies to last subplot (row 2 column 3). I want it to apply to all subplots. I also of course tried calling plt.xticks every time after each subplot, but it doesn’t change anything. Only last one is affected.

Asked By: staticvoid

||

Answers:

I believe using "ID" as index should be a better option, then no need to manually define the xticks:

df = df.set_index('ID')

df['Col1'].plot(ax=axes[0,0], title='Col1')
# ...

plt.show()

If you really want to use your strategy, you need to loop:

for ax in axes.flat:
    ax.set_xticks(df['ID'])

You can also avoid any loop and manual plotting using:

df.set_index('ID').plot(subplots=True, layout=(2, 3))
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.