猿问

并排放置多个地块

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

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

数据:数据

提供代码:

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,只是不要进入专栏。可能吗?感谢您提供任何可能的帮助。


宝慕林4294392
浏览 144回答 2
2回答

大话西游666

您需要将地块分配给 ax ,它也将是 set_title 等:import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltdata = 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)

慕尼黑的夜晚无繁华

我认为你应该使用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
随时随地看视频慕课网APP

相关分类

Python
我要回答