如何使用pandas数据绘制饼图?

3
我目前已成功绘制出了饼图,并使用相对较小的数据帧。 enter image description here 但是,当我尝试绘制pandas饼图时,它看起来非常好,直到我意识到我的索引已被包括在内(请参见右上角和左下角的数字0和1)。

enter image description here

有没有办法删除索引?目前,我非常怀疑问题出在重置和删除旧索引的部分。

这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\tax-and-penalty-arising-from-audits-by-tax-type.csv'
data = pd.read_csv(dataname)
df = pd.DataFrame(data)

# drop the no_of_cases column since we will not be using it
df2 = df.drop(['tax_and_penalty_arising'],axis=1)

# merge the values: individual income tax and corporate income tax together under tax type together as they can be seen to be seperated in some years eg 2011
dictionary = {'Corporate Income Tax':'Individual and Corporate Income Tax','Individual Income Tax':'Individual and Corporate Income Tax'}
df3 = df2.groupby(['financial_year',df2['tax_type'].replace(dictionary)]).sum().reset_index()

# get only the data from the latest financial_year(2018)
df4 = df3[(df3.financial_year == (2018))]
df4 = df4.reset_index(drop=True)

# # drop the column financial_year as we will not be using it
df4 = df4.drop(['financial_year'],axis=1)

# #  print the dataframe   
print(df4)

# plot out the pie chart
# df4 = df4.drop("index",axis=1)
ax = df4.plot.pie(y='no_of_cases',figsize=(10,10))
ax.legend(labels='tax_type')
plt.pie(df4['no_of_cases'],labels=df4['tax_type'],shadow=False,startangle=90, autopct="%1.1f%%")
plt.show()
1个回答

4

首先定义你的 df4:

df4 = pd.DataFrame({"tax_type":["GST", "Individual and Corporate Income Tax"], 
                    "no_of_cases":[3145,7001]})

_, ax = plt.subplots(figsize = (10,10))
wedges,_,_ = ax.pie(df4['no_of_cases']
                    ,labels=df4["tax_type"]
                    ,shadow=False,startangle=90, autopct="%1.1f%%"
                    ,textprops={'fontsize': 16})
ax.legend(wedges,df4["tax_type"], loc="upper center", prop={'size': 16});

enter image description here


嗨嗨。谢谢!我已经尝试了它,而且它有效。但是有没有办法从df3中获取所有数据,而不是重新定义我从df3中过滤出来的值,然后将其放入df4中? - prodoggy4life

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接