gpt4 book ai didi

python - 如何防止matplotlib中左x轴延伸到右x轴?

转载 作者:行者123 更新时间:2023-11-30 22:50:41 34 4
gpt4 key购买 nike

我正在尝试创建两个相邻的直方图。我的问题是左侧标签的 x 标签扩展到右侧标签,如下所示: enter image description here

这是我如何设置情节

import pandas as pd
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(1,1,1)
ax1.set_xlim([min(df1["Age"]),max(df1["Age"])])
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1,2,2)
ax2.set_xlim([min(df2["Age"]),max(df2["Age"])])
ax2 = df2["Age"].hist(color="seagreen")
plt.show()

我希望为每个子图显示一个 x 轴,因此第一个子图将包含从 min(df1["Age"]) 的年龄max(df1["Age"]) 和另一个 x 轴。第二个将包括从 min(df2["Age"])max(df2["Age"]) 的年龄。我怎样才能做到这一点

最佳答案

问题是,使用 ax1 = Fig.add_subplot(1, 1, 1) 添加的第一个子图将填充整个图形。第二个子图 ax2 = Fig.add_subplot(1, 2, 2) 将跨越右侧,就好像左侧有第一个子图(实际上没有)。如果你想要两个子图,宽度为半个图大小,你应该做的是使用

fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1) # first subplot, to the left
ax2 = fig.add_subplot(1, 2, 2) # second subplot, to the right

另一种更简洁的方法是使用 plt.subplots 函数。通过一次调用即可创建图形和两个轴,如下所示:

fig, (ax1, ax2) = plt.subplots(1, 2)

下面三张图片显示了问题所在。第一个图是在您的代码中添加 ax1 后的结果(不是在我的代码中!)。然后加上ax2,得到第二个图,很明显原来的ax1的一半被新的ax2覆盖了。然而,第三个图显示了两个并排的轴,这就是你我的猜测。

澄清编辑:调用plt.add_subplot(rows, cols, num)时,num参数告诉要添加哪个子图。 IE。如果rows = cols = 2num = 1对应左上角,num = 2对应右上角,num = 3 位于左下角,num = 4 位于右下角。这意味着您可以使用 fig.add_subplot(2, 2, 2) 添加右上角的子图(在 2 x 2 网格中),请参见下面的图 4。

Only ax1 added(图 1:仅从代码中添加了 ax1) enter image description here(图 2:从您的代码中添加 ax2) enter image description here(图3:以正确的方式并排添加ax1和ax2) enter image description here(图4:仅添加了右上子图,fig.add_subplot(2, 2, 2)。2 x 2 网格中还有 3 个空点。)

关于python - 如何防止matplotlib中左x轴延伸到右x轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39253464/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com