【问题标题】:Putting several plots side by side并排放置几个地块
【发布时间】:2020-09-17 12:56:59
【问题描述】:

我有 9 个使用 matplotlib.pyplot 制作的直方图。

有没有一种简单的方法可以将它们“粘”在一起,这样每个新的直方图就不会从新行开始?

数据:data

提供代码:

for column in data:
   plt.figure(figsize=(5,5))

   a1 = data[(data['Outcome'] == 0)][column]
   a2 = data[(data['Outcome'] == 1)][column]

   ax = np.linspace(0, data[column].max(), 50)

   plt.hist(a1, ax, color='blue', alpha=0.6, label='Have Diabetes = NO')
   plt.hist(a2, ax, color='yellow', alpha=0.6, label='Have Diabetes = YES')

   plt.title(f'Histogram for {column}')
   plt.xlabel(f'{column}')
   plt.ylabel('number of people')

   plt.grid(True)
   leg = plt.legend(loc='upper right', frameon=True)

我想要的是这样的:

我实际上不需要它是 3x3,只是不要进入列。可能吗?感谢您提供任何可能的帮助。

【问题讨论】:

  • 这是一个非常糟糕的问题,没有任何代码、任何数据、任何关于如何生成这个数字的信息。您当然可以使用fig, ax = plt.subplots(1, 9) 来获取 1 行和 9 列,但是您要如何使用它只取决于您,因为我们没有您的数据和代码
  • 添加了代码,但是,我的问题是关于所有地块,而不是这个特定的地块。

标签: python matplotlib


【解决方案1】:

您需要将绘图分配给 ax ,并且它还将是 set_title 等:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
data = pd.read_csv("datasets_228_482_diabetes.csv")

fig,ax = plt.subplots(3,3,figsize=(9,9))
ax = ax.flatten()

for i,column in enumerate(data.columns):
    a1 = data[(data['Outcome'] == 0)][column]
    a2 = data[(data['Outcome'] == 1)][column]

    ax[i].hist(a1, color='blue', alpha=0.6, label='Have Diabetes = NO')
    ax[i].hist(a2, color='yellow', alpha=0.6, label='Have Diabetes = YES')

    ax[i].set_title('Histogram for '+column)
    ax[i].set_xlabel(f'{column}')
    ax[i].set_ylabel('number of people')

    ax[i].legend(loc='upper right',frameon=True,markerscale=7,fontsize=7)

fig.tight_layout()

如你所见,最后一列的结果相当无用,所以如果你不绘制它,你也可以考虑使用 seaborn:

g = sns.FacetGrid(data=data.melt(id_vars="Outcome"),
                  col="variable",hue="Outcome",sharex=False,sharey=False,
                  col_wrap=4,palette=['blue','yellow'])
g = g.map(plt.hist,"value",alpha=0.7)

【讨论】:

  • 如何将 linspace 中的“num”之类的内容添加到子图中?
  • 对不起 num 是什么?
  • "num: int, optional - 要生成的样本数。默认为 50。必须为非负数"。因此,在 linspace 中,我设置了 num=50,以便我的直方图看起来接近图片。所以,正如你所见,我的列要细得多。使用子图时找不到如何更改它。
  • stackoverflow.com/questions/33458566/…,只是增加垃圾箱。我认为如果您尝试这样做,例如 ax[i].hist(a1,..bins=..) 它应该可以工作
  • 恐怕这与这个问题无关,如果您对此仍有疑问,请将其作为问题发布。
【解决方案2】:

我认为您应该使用axes 而不是pyplot 进行绘图:

 from matplotlib import pyplot as plt
 fig, axes = plt.subplots(3,3, figsize=(9,9))

 for d, ax in zip(data_list, axes.ravel()):
      ax.hist(d)   # or something similar

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2019-01-07
    • 2019-08-14
    • 2017-10-19
    • 1970-01-01
    相关资源
    最近更新 更多