鉴于您的数据
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# plot parameters
plt.style.use('seaborn')
plt.rcParams['figure.figsize'] = (16.0, 10.0)
data = {'country': ['Afghanistan', 'Afghanistan', 'Afghanistan', 'Afghanistan', 'Albania', 'Albania', 'Albania', 'Albania'],
'year': [1975, 1985, 1995, 2005, 1975, 1985, 1995, 2005],
'value': [2127, 3509, 1243, 1327, 4595, 7880, 2087, 4254]}
df = pd.DataFrame(data)
country year value
0 Afghanistan 1975 2127
1 Afghanistan 1985 3509
2 Afghanistan 1995 1243
3 Afghanistan 2005 1327
4 Albania 1975 4595
5 Albania 1985 7880
6 Albania 1995 2087
7 Albania 2005 4254
将seaborn.barplot 与hue 参数一起使用
p = sns.barplot(x='year', y='value', hue='country', data=df)
横向
p = sns.barplot(x='value', y='year', hue='country', data=df, orient='h')
每个国家/地区的单独图
- 使用
plt.subplot(1, 2, i) 行乘以列应该等于唯一国家/地区的数量,如果有奇数则+1。
max_value = df.value.max() + 100 # + 100 to add padding at the top of the plot; 100 is an arbitrary value and can be removed
for i, country in enumerate(df.country.unique(), 1): # iterate through each unique country
data = df[df.country == country] # filter by country
plt.subplot(1, 2, i) # rows, columns, i: plot index beginning at 1
sns.barplot(x='year', y='value', data=data)
plt.ylim(0, max_value) # set y-lim with max of the value column; makes it easier to compare countries
plt.title(country)