如何修改df.plot饼图标签并隐藏DataFrame表格索引?
解决Pandas饼图标签、DataFrame显示及图例问题
问题1:饼图标签替换为State/UT字段内容
pandas的pie绘图中x参数不适用,需通过labels参数直接指定State/UT列作为饼图标签。同时饼图无需横轴/纵轴标签,可移除冗余的plt.xlabel和plt.ylabel。
问题2:打印DataFrame时隐藏索引、显示排名
先给DataFrame添加从1开始的Rank列,再用to_string(index=False)打印,即可隐藏默认索引,只显示包含排名的列。
问题3:将州排名设为饼图图例
通过legend参数传入排名与州名的组合文本,让图例清晰展示每个州的排名信息。
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("top_10_states_2020.csv") # 添加排名列 df["Rank"] = range(1, len(df) + 1) print("Pie Chart => Top 10 most visited states of India by foreign tourists (in 2020)") # 隐藏索引打印DataFrame print(df.to_string(index=False)) # 绘制饼图,指定标签、图例,优化显示 ax = df.plot( kind="pie", y="No. of tourists", labels=df["State/UT"], autopct="%.1f%%", # 可选:显示饼块百分比 legend=[f"Rank {row['Rank']}: {row['State/UT']}" for _, row in df.iterrows()], title="Top 10 most visited states of India by foreign tourists (in 2020)" ) # 清除pandas自动生成的冗余纵轴标签 ax.set_ylabel("") plt.show()
关键修改说明
df["Rank"] = range(1, len(df)+1):生成1到10的连续排名列df.to_string(index=False):隐藏默认索引,只展示含排名的表格内容- 饼图移除
x参数,改用labels=df["State/UT"]指定饼块显示的地区名称 legend参数拼接排名与州名,生成带排名信息的图例autopct参数可选添加百分比显示,提升饼图可读性ax.set_ylabel(""):清除pandas自动添加的无意义y轴标签
内容的提问来源于stack exchange,提问作者Annika Kamath
相关产品推荐
相关产品推荐

