我正在尝试使用以下代码绘制相同的两列的图表:
plt.figure(figsize = (3,3))
df["gender", "heart_disease"].plot(kind = "bar")
plt.xlabel("heart_disease") plt.ylabel("gender")
问题是你没有按性别分组:
import pandas as pd
import matplotlib.pyplot as plt
data = {
'gender': ['Male', 'Female', 'Male', 'Female', 'Male'],
'heart_disease': [1, 0, 1, 0, 1]
}
df = pd.DataFrame(data)
plt.figure(figsize = (3,3))
df.groupby("gender")["heart_disease"].sum().plot(kind="bar")
plt.xlabel("heart_disease")
plt.ylabel("gender")
plt.show()
Male
或Female
,未捕获。
Male
和 Female
主题具有或不具有 heart_disease
的行:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
"gender": [...],
"heart_disease": [...]
})
x = ["Male", "Female"]
y = [0,0] # Where index 0 is Male and index 1 is Female
for index, row in df.iterrows():
if row["gender"] == "Male" and row["heart_disease"] == 1:
y[0] += 1
if row["gender"] == "Female" and row["heart_disease"] == 1:
y[1] += 1
plt.bar(x,y, color = "black", edgecolor = "red")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.show()
此方法的文档以及@Mark描述的方法可以在这里找到:
Pandas 行迭代器# 迭代器
Pandas GroupBy #@Mark 的参考