尝试使用forloops在子图中绘制散点图

2024-05-15 04:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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


Tags: 数据infor地方rangepltvariablefat
1条回答
网友
1楼 · 发布于 2024-05-15 04:16:18

使用此代码:

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

相关问题 更多 >

    热门问题