Home > front end >  Show all xlabels and xticks in Matplotlib
Show all xlabels and xticks in Matplotlib

Time:09-17

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!

CodePudding user response:

You just need to call plt.tight_layout() after your loop. Refer to Tight layout

  • Related