Python 带数据框的条形图
Python bar chart with dataframe
我有以下数据框:
df = pd.DataFrame(dict(
A=[1, 0, 0, 1],
B=[0, 1, 1, 1],
C=[1, 0, 0, 0]
))
如何在一张图中绘制 1 和 0 的海数的条形图,请参见:
从您提供的数据集开始:
df = pd.DataFrame(dict(
A=[1, 0, 0, 1],
B=[0, 1, 1, 1],
C=[1, 0, 0, 0]
))
你应该用 pandas.melt
:
重新塑造数据框
df = pd.melt(frame = df,
var_name = 'class',
value_name = 'survived')
class survived
0 A 1
1 A 0
2 A 0
3 A 1
4 B 0
5 B 1
6 B 1
7 B 1
8 C 1
9 C 0
10 C 0
11 C 0
所以你可以使用seaborn.countplot
得到你想要的情节:
fig, ax = plt.subplots()
sns.countplot(ax = ax, data = df, x = 'class', hue = 'survived')
plt.show()
完整代码
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(dict(
A=[1, 0, 0, 1],
B=[0, 1, 1, 1],
C=[1, 0, 0, 0]
))
df = pd.melt(frame = df,
var_name = 'class',
value_name = 'survived')
fig, ax = plt.subplots()
sns.countplot(ax = ax, data = df, x = 'class', hue = 'survived')
plt.show()
我有以下数据框:
df = pd.DataFrame(dict(
A=[1, 0, 0, 1],
B=[0, 1, 1, 1],
C=[1, 0, 0, 0]
))
如何在一张图中绘制 1 和 0 的海数的条形图,请参见:
从您提供的数据集开始:
df = pd.DataFrame(dict(
A=[1, 0, 0, 1],
B=[0, 1, 1, 1],
C=[1, 0, 0, 0]
))
你应该用 pandas.melt
:
df = pd.melt(frame = df,
var_name = 'class',
value_name = 'survived')
class survived
0 A 1
1 A 0
2 A 0
3 A 1
4 B 0
5 B 1
6 B 1
7 B 1
8 C 1
9 C 0
10 C 0
11 C 0
所以你可以使用seaborn.countplot
得到你想要的情节:
fig, ax = plt.subplots()
sns.countplot(ax = ax, data = df, x = 'class', hue = 'survived')
plt.show()
完整代码
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(dict(
A=[1, 0, 0, 1],
B=[0, 1, 1, 1],
C=[1, 0, 0, 0]
))
df = pd.melt(frame = df,
var_name = 'class',
value_name = 'survived')
fig, ax = plt.subplots()
sns.countplot(ax = ax, data = df, x = 'class', hue = 'survived')
plt.show()