【问题标题】:Show all xlabels and xticks in Matplotlib显示 Matplotlib 中的所有 xlabels 和 xticks
【发布时间】:2021-11-11 20:05:07
【问题描述】:

我正在尝试使用matplotlib.pyplotsubplot 在单个窗格上绘制多个图形。这是我当前的代码。

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

如果我取消注释这两行,那么所有xlabels 都会出现,但最上面一行的xticks 会消失。我认为这是因为[label_outer][2] 函数“释放”了空间

我不明白如何才能将两者都放在第一行。如果打印出所有的xlabels,那么它们确实都在那里。

任何帮助将不胜感激!

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    您只需要在循环之后调用plt.tight_layout()。请参阅the guide 了解有关选项和功能的更多信息。

    【讨论】:

    • 非常感谢!我花了很长时间寻找这个,但找不到它:(
    • 现在,您知道如果您有布局问题,请使用tight_layout :-)
    • 是的!确实。 tight 布局应该允许显示 more 文本似乎非常违反直觉。我以后肯定会参考该指南!
    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 2020-04-21
    • 2016-05-14
    • 1970-01-01
    • 2012-10-11
    • 2011-01-25
    • 2018-08-05
    相关资源
    最近更新 更多