gpt4 book ai didi

python - for 循环生成多个 polyfit 散点图

转载 作者:行者123 更新时间:2023-11-28 17:38:01 25 4
gpt4 key购买 nike

我有一个包含 20 列的数据框。我希望创建散点图,每个散点图都有一条最合适的线。 x 列将保持不变,我想使用 for 循环遍历数据框中的每个其他列。结果将是 19 个散点图。

我当前的设置看起来像这样:

columns = [1,2,3,4,5,6,7...20]
for column in columns:
x= df[another column from the dataframe]
y= df[column]
fit = polyfit(x,y,1)
fitx = poly1d(fit)
plt.plot(x,y,'b+',
x,fitx(x),'b-')

这会在单个轴上绘制 19 条最佳拟合线,而不是创建 19 个轴。关于如何解决此问题的任何想法?

最佳答案

您必须明确地创建每个子图。在此玩具代码中,我使用了一个 4x5 网格,这导致最后一个图为空。

子图是用 plt.subplots(nrows, ncols, ...) 创建的。我对 4x5 的选择是任意的。您可以通过更改行数和列数轻松调整网格。

from itertools import chain

import numpy as np
import pandas as pd
import matplotlib.pylab as plt
np.random.seed(42)

# prepare sample data
columns = ["col" + str(i) for i in range(1, 21)]
data = {col: np.random.rand(10) for col in columns}
df = pd.DataFrame(data)


x_column = "col1"
cols = columns[:]
cols.remove(x_column)

plt, axes = plt.subplots(4, 5, sharex=True, sharey=True, figsize=(12,12))
flat_axes = chain(*axes)

for y_column, ax in zip(cols, flat_axes):
if y_column != x_column:
x = df[x_column]
y = df[y_column]
fit = np.polyfit(x, y, 1)
fitx = np.poly1d(fit)
ax.plot(x, y, 'b+', x, fitx(x),'b-')

这是结果: plot

关于python - for 循环生成多个 polyfit 散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28488885/

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