如何在Python上为男性和女性创建2个图形

时间:2018-04-04 04:42:53

标签: matplotlib

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv("titanic.csv")

plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot (df(x="Age", y="Sex", color='purple'))
plt.ylabel('Male')
plt.xlabel('Age Group')
plt.title('Male that went Aboard')

plt.subplot(1, 2, 2)
plt.plot(df(x='Age', y='Sex',color='green'))
plt.ylabel('Female')
plt.xlabel('Age Group')
plt.title('Female that went Aboard')
plt.show()

我想在“性别”下的2个不同图表上查看男性和女性 但收到错误: 感谢

2 个答案:

答案 0 :(得分:0)

请尝试以下代码:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv("/home/vermap/test.csv")
plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.plot(list(df[df['Sex'].isin(["Male"])]['Age']), "-o", color='purple')
plt.xlabel('Age Group')
plt.title('Male that went Aboard')

plt.subplot(1, 2, 2)
plt.plot(list(df[df['Sex'].isin(["Female"])]['Age']), "-o", color='green')
plt.xlabel('Age Group')
plt.title('Female that went Aboard')
plt.show()

如果您有任何疑问,请与我们联系。

答案 1 :(得分:0)

以下代码解决了我的问题。

感谢您的回复!

将matplotlib.pyplot导入为plt 将pandas导入为pd

df = pd.read_csv("titanic.csv")
plt.figure(figsize=(10, 5))
df = pd.get_dummies(df, columns=['Sex'])
plt.subplot(1, 2, 1)
plt.hist(df[df['Sex'].isin["Male"]]['Age'], "-o", color='purple')
plt.xlabel('Age Group')
plt.title('Male that went Aboard')

plt.subplot(1, 2, 2)
plt.hist(df[df['Sex'].isin["Female"]]['Age'], "-o", color='green')
plt.xlabel('Age Group')
plt.title('Female that went Aboard')
plt.show()