尝试使用for循环在子图中绘制散点图

问题描述 投票:2回答:1

我正在尝试使用for循环使子图遍历数据帧中的x变量。所有图都是散点图。

X-variable: 'Protein', 'Fat', 'Sodium', 'Fiber', 'Carbo', 'Sugars' 
y-variable: 'Cal'

这是我被困住的地方

plt.subplot(2, 3, 2)
for i in range(3):
     plt.scatter(i,sub['Cal'])

enter image description here

python loops for-loop matplotlib subplot
1个回答
2
投票

使用此代码:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data.csv')
columns = list(df.columns)
columns.remove('Cal')

fig, ax = plt.subplots(1, len(columns), figsize = (20, 5))

for idx, col in enumerate(columns, 0):
    ax[idx].plot(df['Cal'], df[col], 'o')
    ax[idx].set_xlabel('Cal')
    ax[idx].set_title(col)

plt.show()

我得到了散点图的这个子图:

enter image description here

但是,也许最好使用单个散点图并使用标记颜色来区分数据类型。看到此代码:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_style('darkgrid')

df = pd.read_csv('data.csv')
# df.drop(columns = ['Sodium'], inplace = True)  # <--- removes 'Sodium' column
table = df.melt('Cal', var_name = 'Type')

fig, ax = plt.subplots(1, 1, figsize = (10, 10))
sns.scatterplot(data = table,
                x = 'Cal',
                y = 'value',
                hue = 'Type',
                s = 200,
                alpha = 0.5)

plt.show()

给出所有数据在一起的图:

enter image description here

'Sodium'值到目前为止与其他值不同,因此,如果用此行删除此列:

df.drop(columns = ['Sodium'], inplace = True)

您将获得更具可读性的情节:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.