显示 Matplotlib 中的所有 x 轴标签和刻度。

3

我正在尝试使用matplotlib.pyplot中的subplot在单一面板上绘制多个图像。以下是我的当前代码。

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)

当前代码中,当以下两行代码被注释掉时,它会打印出所有的xticks,但仅为底部两个图绘制xlabels

enter image description here

如果取消对这两行代码的注释,则所有xlabels都会出现,但顶部行的xticks会消失。我认为这是由于[label_outer][2]函数释放了空间。

enter image description here

我不知道如何在顶部行同时显示这两者。如果输出所有的xlabels,则它们确实都存在。
任何帮助将不胜感激!
1个回答

3

在你的循环之后,只需要调用plt.tight_layout()。有关选项和功能的详细信息,请参阅指南

Tight layout


非常感谢!我花了很长时间寻找这个,但是找不到 :( - Sam OT
现在,你知道如果你有布局问题,可以使用 tight_layout :-) - Corralien
是的!确实如此。紧凑的布局似乎很反直觉,却能够显示更多的文本。我将来肯定会参考那个指南! - Sam OT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接