如何使用 for 循环绘制多个图

Bha*_*der 4 python matplotlib seaborn

a=pd.DataFrame({'length':[20,10,30,40,50],
                'width':[5,10,15,20,25],
                'height':[7,14,21,28,35]})

for i,feature in enumerate(a,1):
    sns.regplot(x = feature,y= 'height',data = a)
    print("{} plotting {} ".format(i,feature))
Run Code Online (Sandbox Code Playgroud)

我想用三个不同的列绘制 3 个不同的图,即 x 轴上的“长度”、“宽度”和“高度”以及 y 轴上的“高度”。
这是我编写的代码,但它重叠了 3 个不同的图。我打算绘制 3 个不同的图。

dan*_*joo 5

这取决于你想做什么。如果您想要多个单独的图,您可以为每个数据集创建一个新图形:

import matplotlib.pyplot as plt
for i, feature in enumerate(a, 1):
    plt.figure()  # forces a new figure
    sns.regplot(data=a, x=feature, y='height')
    print("{} plotting {} ".format(i,feature))
Run Code Online (Sandbox Code Playgroud)

或者,您可以将它们全部绘制在同一个图形上,但在不同的子图中。IE 彼此相邻:

import matplotlib.pyplot as plt
# create a figure with 3 subplots
fig, axes = plt.subplots(1, a.shape[1])
for i, (feature, ax) in enumerate(zip(a, axes), 1):
    sns.regplot(data=a, x=feature, y='height', ax=ax)
    print("{} plotting {} ".format(i,feature))
Run Code Online (Sandbox Code Playgroud)

3块地块彼此相邻

plt.subplots有几个选项可以让您按照自己喜欢的方式对齐绘图。检查文档以获取更多信息!