python - 前 5 列,共 2 列
问题描述
我想并排显示两个图表,其中包含前 5 部最受欢迎的法国剧集和前 5 部最受欢迎的法国电影。
系列或电影的票数 numVotes 将被视为其受欢迎程度的可靠指标。
top_france_tv = pd.Series(df[df['country'] == 'France']
ax = sns.countplot(y=top_france_tv, order=top_france_tv.value_counts().iloc[:5].index)
ax.tick_params(axis='y', length=0)
plt.tight_layout()
plt.show()
解决方案
您可以取其中top_france_tv
的电影子集,然后按排序averageRating
并取前 5 个。将其用作barplot
放映title
和的数据框averageRating
。重复电视节目。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
sns.set()
np.random.seed(123)
df = pd.DataFrame({'type': np.random.choice(['Movie', 'TV Show'], 100),
'title': ["".join(np.random.choice([*'uvwxyz '], np.random.randint(5, 20))) for _ in range(100)],
'averageRating': np.random.uniform(1, 10, 100).round(1),
'country': np.random.choice(['France', 'other country'], 100)})
top_france_tv = df[df['country'] == 'France']
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 3), sharex=True)
for ax, mov_type in zip((ax1, ax2), ['Movie', 'TV Show']):
df_best_5 = top_france_tv[top_france_tv['type'] == mov_type].sort_values('averageRating', ascending=False)[:5]
sns.barplot(data=df_best_5, y='title', x='averageRating', palette='rocket', ax=ax)
ax.set_title('Best 5 French ' + mov_type + 's')
ax.set_ylabel('')
plt.tight_layout()
plt.show()