如何用Pandas绘制音乐榜艺术家排名多条形图并解决报错?
解决方法
首先,你的报错说明DataFrame中不存在名为Highest_Charting_Position的列,先执行以下代码确认你的实际列名:
print(top_artists.columns)
后续代码中的列名请替换为你查出的真实列名(比如Rank或其他)。
正确实现步骤
假设你的DataFrame包含两列:Artist(艺术家名称)和Highest_Charting_Position(最高排名),按以下步骤绘制符合需求的多条形图:
- 导入依赖库
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns
- 整理数据格式
将数据按排名分组,转换为适合多条形图的透视表(同一排名下的艺术家会在对应y轴位置并排显示):
# 透视数据:索引为排名,列为艺术家,值标记该艺术家是否在该排名 pivot_df = top_artists.pivot_table( index='Highest_Charting_Position', columns='Artist', aggfunc='size', fill_value=0 )
- 绘制横向多条形图
# 设置图形大小 plt.figure(figsize=(12, 10)) # 绘制多条形图 pivot_df.plot(kind='barh', stacked=False, cmap='flare', width=0.8) # 调整y轴:显示1-20的排名,反转y轴让排名1在最上方 plt.yticks(range(1, 21)) plt.gca().invert_yaxis() # 设置标签与标题 plt.xlabel('艺术家') plt.ylabel('最高音乐榜排名') plt.title('艺术家最高排名分布') # 调整图例位置避免遮挡 plt.legend(title='艺术家', bbox_to_anchor=(1.05, 1), loc='upper left') # 自动调整布局 plt.tight_layout() plt.show()
简化版:每个艺术家对应单个条形(y轴为排名)
如果不需要同一排名的艺术家并排,仅需每个艺术家的条形对应其排名,可使用以下代码:
plt.figure(figsize=(10, 8)) # 绘制每个艺术家的条形,y轴为排名,x轴为艺术家索引 plt.barh(range(len(top_artists)), top_artists['Highest_Charting_Position'], color=sns.color_palette("flare", len(top_artists))) # 设置y轴刻度为艺术家名称 plt.yticks(range(len(top_artists)), top_artists['Artist']) # 反转y轴让排名1在最上方 plt.gca().invert_yaxis() plt.xlabel('最高排名') plt.ylabel('艺术家') plt.title('艺术家最高音乐榜排名') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Iasmina Tatar
相关产品推荐
相关产品推荐

