Man*_*lai 9 python matplotlib pandas pie-chart
我有数据如下:
ID Gender Country ...
1 Male UK
2 Female US
3 Male NZ
4 Female UK
...
Run Code Online (Sandbox Code Playgroud)
性别只有 2 个选项,国家只有 3 个选项。我想为“性别”和“国家”创建一个单独的饼图,以显示每个选项在数据中出现的次数,但我对如何做到这一点感到非常困惑。
数据存储在 pandas 数据框中。
非常感谢任何和所有的帮助!
Joh*_*anC 12
这是使用pandas 的方法:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
def label_function(val):
return f'{val / 100 * len(df):.0f}\n{val:.0f}%'
N = 50
df = pd.DataFrame({'country': np.random.choice(['UK', 'US', 'NZ'], N),
'gender': np.random.choice(['Male', 'Female'], N)})
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
df.groupby('country').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20},
colors=['tomato', 'gold', 'skyblue'], ax=ax1)
df.groupby('gender').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20},
colors=['violet', 'lime'], ax=ax2)
ax1.set_ylabel('Per country', size=22)
ax2.set_ylabel('Per gender', size=22)plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
PS:要仅显示百分比,请使用autopct='%1.0f%%'
。
小智 7
我假设你是从这个开始的
import pandas as pd
from matplotlib.pyplot import pie, axis, show
df = pd.DataFrame([[1,'Male','UK'], [2, 'Female', 'NZ'], [3, 'Male', 'UK'], [4, 'Male', 'US']], columns=['ID', 'Gender', 'Country'])
Run Code Online (Sandbox Code Playgroud)
性别图
df.groupby('gender').size().plot(kind='pie', autopct='%.2f')
Run Code Online (Sandbox Code Playgroud)
国家情节
df.groupby('country').size().plot(kind='pie', autopct='%.2f')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27617 次 |
最近记录: |