gpt4 book ai didi

python - 在网格中绘制多个直方图

转载 作者:行者123 更新时间:2023-11-28 19:32:35 25 4
gpt4 key购买 nike

我正在运行以下代码以在 3 x 3 网格中为 9 个变量绘制直方图。但是,它只绘制一个变量。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def draw_histograms(df, variables, n_rows, n_cols):
fig=plt.figure()
for i, var_name in enumerate(variables):
ax=fig.add_subplot(n_rows,n_cols,i+1)
df[var_name].hist(bins=10,ax=ax)
plt.title(var_name+"Distribution")
plt.show()

最佳答案

您正在正确添加子图,但您为每个添加的子图调用 plt.show,这会导致显示到目前为止绘制的内容,即一个图。例如,如果您在 IPython 中内联绘图,您将只会看到最后绘制的绘图。

Matplotlib 提供了一些不错的 examples如何使用子图。

您的问题已解决:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def draw_histograms(df, variables, n_rows, n_cols):
fig=plt.figure()
for i, var_name in enumerate(variables):
ax=fig.add_subplot(n_rows,n_cols,i+1)
df[var_name].hist(bins=10,ax=ax)
ax.set_title(var_name+" Distribution")
fig.tight_layout() # Improves appearance a bit.
plt.show()

test = pd.DataFrame(np.random.randn(30, 9), columns=map(str, range(9)))
draw_histograms(test, test.columns, 3, 3)

它给出了这样一个情节:

subplot histograms

关于python - 在网格中绘制多个直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29530355/

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