gpt4 book ai didi

python - 如何以编程方式绘制多个变量

转载 作者:行者123 更新时间:2023-12-04 01:13:19 25 4
gpt4 key购买 nike

我想针对单个因变量绘制多个自变量并在一个图中显示它们。下面的代码有效,但我有超过 4 个变量。所以手工做所有的变量会很麻烦。有任何想法吗?谢谢!

fig, axs = plt.subplots(2, 2, figsize=(10, 6))

axs[0, 0].scatter(df.ind_var1, df.dep_var)
axs[0, 1].scatter(df.ind_var2, df.dep_var)
axs[1, 0].scatter(df.ind_var3, df.dep_var)
axs[1, 1].scatter(df.ind_var4, df.dep_var)

axs[0, 0].set_title('ind_var1')
axs[0, 1].set_title('ind_var2')
axs[1, 0].set_title('ind_var3')
axs[1, 1].set_title('ind_var4')

for ax in axs.flat:
ax.set_xticklabels([])
ax.set_ylabel('dep_var')
ax.set_yticklabels([])

fig.suptitle('Plot', fontsize=20)
fig.tight_layout()

plt.show()

最佳答案

看起来你可以这样做:

# you need to provide this
ind_vars = ['ind_var1', 'ind_var2', 'ind_var3', 'ind_var4']

fig, axes = plt.subplots(2,2, figsize=(10,6))

# this combines the two loops
for col, ax in zip(ind_vars, axes.ravel()):
# plot the data
ax.scatter(df[col], df['dep_var'])

# format the axis
ax.set_title(col)
ax.set_xticklabels([])
ax.set_ylabel('dep_var')
ax.set_yticklabels([])

fig.suptitle('Plot', fontsize=20)
fig.tight_layout()

plt.show()

关于python - 如何以编程方式绘制多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64125589/

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