My Data Frame这是我的数据框
release_year genre count
0 1960 Drama 13
1 1961 Drama 16
2 1962 Drama 21
3 1963 Drama 13
.
.
.
6 1966 Comedy 16
这是我的代码
fig = plt.figure(figsize=(20, 6))
title = fig.suptitle("Which genres are most popular from year to year?", fontsize=14,
fontweight='bold')
fig.subplots_adjust(top=0.9, wspace=0.3)
ax = fig.add_subplot(1,1,1)
ax.set_xlabel("Year")
ax.set_ylabel("Production Count")
ax.tick_params(axis='both', which='major', labelsize=8.5)
bar = ax.bar(popular['release_year'], # i.e. [6, 5, 7, 4, 8, 3, 9]
popular['count'], # i.e. [2836, 2138, 1079, 216, 193, 30, 5]
edgecolor='black', linewidth=1)
My Bar Graph 这就是我得到的
如何获得图中的“类型”列?有两种不同的类型(戏剧和喜剧),我希望每个条形都根据其所属的类别进行颜色分类。我也想在顶部贴上标签,以便可以将其形象化。
非常感谢。
直接使用matplotlib,您可以按如下所示对条进行着色。创建图例需要一些custom code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.patches import Patch
years = range(1960, 1991)
popular = pd.DataFrame({'release_year': years,
'genre': np.random.choice(['Drama', 'Comedy'], len(years)),
'count': np.random.randint(20, 50, len(years))})
fig = plt.figure(figsize=(20, 6))
title = fig.suptitle("Which genres are most popular from year to year?", fontsize=14,
fontweight='bold')
fig.subplots_adjust(top=0.9, wspace=0.3)
ax = fig.add_subplot(1, 1, 1)
genre_color = {'Drama': 'crimson', 'Comedy': 'limegreen'}
ax.bar(popular['release_year'],
popular['count'],
color=[genre_color[i] for i in popular['genre']],
edgecolor='black', linewidth=1)
ax.set_xlabel("Year")
ax.set_ylabel("Production Count")
ax.tick_params(axis='both', which='major', labelsize=8.5)
legend_elements = [Patch(facecolor=genre_color[gen], edgecolor='b', label=gen)
for gen in genre_color]
ax.legend(handles=legend_elements)
plt.show()
PS:Seaborn还具有一些生成条形图的标准功能(dodge=False
防止代码要求每年使用单独的流派列)。请注意,通常更改刻度和标签最好在创建条形图之后而不是在此之前进行。例如。 Seaborn设置了自己的标签,之后可以更改它们。
import seaborn as sns
sns.barplot(x='release_year', y='count', data=popular, hue='genre', palette=genre_color, dodge=False)