[英]How to plot a pie chart in matplotlib with 3 columns?
I need to plot a pie chart using matplotlib but my DataFrame
has 3 columns namely gender
, segment
and total_amount
. 我需要使用matplotlib绘制饼图,但我的DataFrame
包含3列,即“ gender
,“ segment
和“ total_amount
。 I have tried playing with plt.pie()
arguments but it only takes x and labels for data. 我尝试过使用plt.pie()
参数,但是它只使用x和标签作为数据。 I tried setting gender
as a legend but then it doesn't look right. 我尝试将gender
设置为图例,但看起来不正确。
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'gender': {0: 'Female',
1: 'Female',
2: 'Female',
3: 'Male',
4: 'Male',
5: 'Male'},
'Segment': {0: 'Gold',
1: 'Platinum',
2: 'Silver',
3: 'Gold',
4: 'Platinum',
5: 'Silver'},
'total_amount': {0: 2110045.0,
1: 2369722.0,
2: 1897545.0,
3: 2655970.0,
4: 2096445.0,
5: 2347134.0}})
plt.pie(data = df,x="claim_amount",labels="Segment")
plt.legend(d3.gender)
plt.show()
The result I want is a pie chart of total_amount
and its labels as gender
and segment
. 我想要的结果是一个total_amount
的饼图,其标签为gender
和segment
。 If I can get the percentage, it will be a bonus. 如果我能得到这个百分比,那将是一个奖金。
I suggest the following: 我建议以下内容:
# Data to plot
# Take the information from the segment and label columns and join them into one string
labels = df["Segment"]+ " " + df["gender"].map(str)
# Extract the sizes of the segments
sizes = df["total_amount"]
# Plot with labels and percentage
plt.pie(sizes, labels=labels,autopct='%1.1f%%')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.