python - 如何将一列设置为顶部带有标签的颜色(色调)
问题描述
我的数据框
这是我的数据框
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)
我的条形图 这就是我得到的
如何让情节中包含“流派”列?有两种不同的类型(戏剧和喜剧),我希望每个条都根据它们所属的颜色对颜色进行分类。我想在顶部也制作一个标签,以便可以很好地可视化。
非常感谢你。
解决方案
直接使用 matplotlib,您可以为条形着色,如下所示。创建图例需要一些自定义代码:
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)
推荐阅读
- c++ - C++ 中的 cin.ignore() 函数不适用于整个流
- java - 覆盖 Micronaut 测试中的依赖项
- json - 如何在 google colaboratory 中编辑 dataset-metadata.jason 文件的内容
- javascript - 将值从多维数组传递到对象
- python - Django - 数据库设计
- html - jinja 中的 set 和 with 有什么区别
- reactjs - 可以使用 WebStorm 和 JavaScript 将类组件提取到单独的文件中吗?
- android-studio - 构建 apk 成功但在设备和模拟器上崩溃
- laravel - 在轮播 laravel 中显示和隐藏上一个和下一个元素
- php - PHP if 条件与日期 wordpress 小部件