带条形的分面条形图在 pandas 中并排
Facet barplot with bars are side-by-side in pandas
这行得通,但是在 pandas 中,没有更好的方法来将条形图与条形图并排在一起吗?我觉得可能有一种使用多索引和子图参数编写的简洁方法?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'group': ['A', 'A', 'B', 'B'],
'name': ['name1', 'name2', 'name3', 'name4'],
'2016': [1, 2, 3, 4],
'2017': [1.2, 2.1, 3.0, 4.9]})
df.set_index(['name'], inplace=True)
fig, ax = plt.subplots(2)
group_a = df[df.group == 'A']
group_b = df[df.group == 'B']
group_a.plot(kind='bar', rot=0, ax=ax[0])
group_b.plot(kind='bar', rot=0, ax=ax[1])
如果你想多次做某事,总是值得考虑使用函数和循环。这里,一个循环就够了。
groups = df.group.unique()
fig, ax = plt.subplots(len(groups))
for i, group in enumerate(groups):
df[df.group == group].plot(kind='bar', rot=0, ax=ax[i])
这行得通,但是在 pandas 中,没有更好的方法来将条形图与条形图并排在一起吗?我觉得可能有一种使用多索引和子图参数编写的简洁方法?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'group': ['A', 'A', 'B', 'B'],
'name': ['name1', 'name2', 'name3', 'name4'],
'2016': [1, 2, 3, 4],
'2017': [1.2, 2.1, 3.0, 4.9]})
df.set_index(['name'], inplace=True)
fig, ax = plt.subplots(2)
group_a = df[df.group == 'A']
group_b = df[df.group == 'B']
group_a.plot(kind='bar', rot=0, ax=ax[0])
group_b.plot(kind='bar', rot=0, ax=ax[1])
如果你想多次做某事,总是值得考虑使用函数和循环。这里,一个循环就够了。
groups = df.group.unique()
fig, ax = plt.subplots(len(groups))
for i, group in enumerate(groups):
df[df.group == group].plot(kind='bar', rot=0, ax=ax[i])