Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show all xlabels and xticks in Matplotlib

I am trying to plot multiple figures on a single pane using matplotlib.pyplot's subplot. Here is my current code.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"col1": [1,2], "col2": [3,4], "col3": [5,6], "col4": [7,8], "target": [9,10]})

f, axs = plt.subplots(nrows = 2, ncols = 2, sharey = True)

# for ax in axs.flat:
#     ax.label_outer()

for k, col in enumerate(df.columns):
    if col != "target":
        idx = np.unravel_index(k, (2,2))
        axs[idx].scatter(df[col], df.target)
        axs[idx].set_xlabel(col)

As it stands, with the two lines commented out, this prints all the xticks but only the xlabels for the bottom two plots.

enter image description here

If I uncomment those two lines, then the all the xlabels appear, but the xticks on the top row disappear. I think this is because the space has been 'freed up' by the [label_outer][2] function

enter image description here

I don't see how I can have both on the top row. If one prints out all the xlabels, then they are indeed all there.

Any help would be most appreciated!

like image 331
Sam OT Avatar asked Jan 31 '26 07:01

Sam OT


1 Answers

You just need to call plt.tight_layout() after your loop. Refer to the guide to know more about options and capabilities.

Tight layout

like image 200
Corralien Avatar answered Feb 02 '26 22:02

Corralien