我有 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,只是不要进入一个列。是否有可能?感谢您提供任何可能的帮助。
您需要将图分配给 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句