【问题标题】:Seaborn not working as expected with matplotlib subplotsSeaborn 在 matplotlib 子图中无法正常工作
【发布时间】:2023-03-12 04:14:01
【问题描述】:

我正在尝试在 matplotlib 子图中绘制多个 seaborn regplots,如下所示:

fig, axs = plt.subplots(nrows = 5, ncols=3)
axs = axs.flatten()

for i in range(5):
    df1 = {'a': np.random.rand(100), 'b': np.random.rand(100)}
    df2 = {'a': np.random.rand(100), 'b': np.random.rand(100)}
    df3 = {'a': np.random.rand(100), 'b': np.random.rand(100)}
    sns.set(rc={'figure.figsize':(30,50)})
    sns.regplot(df1['a'], df1['b'], ax = axs[i])
    sns.regplot(df2['a'], df2['b'], ax = axs[i+1])
    sns.regplot(df3['a'], df3['b'], ax = axs[i+2])

但是,我没有得到 15 个子图,而是得到了 5 个数据,这些数据以某种奇怪的组合相互叠加。有人可以解释我做错了什么以及为什么这些情节特别像这样吗? Example of what kind of plot I'm getting

谢谢!

【问题讨论】:

  • 在第一个循环运行中,您填充轴 0、1、2。在下一个您填写 1,2,3 等,最后您填写 4,5,6。所以轴 0 和 6 得到一个地块,1 和 5 得到两个地块,2 和 4 得到三个地块,而 3 得到四个地块。
  • 感谢您的解释!所以本质上,我的代码没有正确分配地块?
  • 使用axs[i*3+n] 而不是axs[i+n] 其中n=[0,1,2]。它应该可以正常工作。
  • 或者试试for i in range(0,15,3)

标签: python matplotlib seaborn


【解决方案1】:

非常感谢 qmaruf,您的回答完美。

这里转载:

fig, axs = plt.subplots(nrows = 5, ncols=3)
axs = axs.flatten()

for i in range(5):
    df1 = {'a': np.random.rand(100), 'b': np.random.rand(100)}
    df2 = {'a': np.random.rand(100), 'b': np.random.rand(100)}
    df3 = {'a': np.random.rand(100), 'b': np.random.rand(100)}
    sns.set(rc={'figure.figsize':(30,50)})
    sns.regplot(df1['a'], df1['b'], ax = axs[i*3])
    sns.regplot(df2['a'], df2['b'], ax = axs[i*3+1])
    sns.regplot(df3['a'], df3['b'], ax = axs[i*3+2])

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2018-11-11
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2019-06-20
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多