如何在python中在一个绘图中显示多个数据?

2024-09-30 00:22:33 发布

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

我使用的是二进制分类数据集。我想要一个计划,第一栏显示人们的年龄,下一栏显示一年级学生的年龄,第三栏显示二年级学生的年龄。请告诉我该怎么做

age | class
------------
 1 |  1
 2 |  1
 3 |  0
 4 |  1
 5 |  0
 6 |  1
 7 |  1
 8 |  0
 9 |  0
10 |  1



import pandas as pd
import matplotlib.pyplot as plt


df = pd.read_csv (r'test.csv')

firstClassDf = df[df['class'] == '0']
print(firstClassDf.shape)

print(firstClassDf.head())


secondClassDf = df[df['class'] == '1']
print(secondClassDf.shape)

boxplot1 = df.boxplot(column='age')
plt.figure()

boxplot2 = firstClassDf.boxplot(column='age')
plt.figure()

boxplot3 = secondClassDf.boxplot(column='age')
plt.figure()

print(plt.show())

预期绘图enter image description here


Tags: importdfageascolumnplt学生class
1条回答
网友
1楼 · 发布于 2024-09-30 00:22:33

从评论中,我了解到您正在寻找以下内容:

import pandas as pd
import matplotlib.pyplot as plt

data = [['age', 'class'],
 [1,1],
 [2,1],
 [3,0],
 [4,1],
 [5,0],
 [6,1],
 [7,1],
 [8,0],
 [9,0],
[10,1]]

df = pd.DataFrame(data[1:])
df.columns = data[0]

bar1 = df['age'].mean()
bar2 = df[df['class'] == 0]['age'].mean()
bar3 = df[df['class'] == 1]['age'].mean()
labels = ['all', 'class1', 'class2']

print (plt.bar(labels, [bar1,bar2,bar3]))

相关问题 更多 >

    热门问题