如何用字典创建华夫饼图

问题描述 投票:1回答:1

我正在通过Jupyter实验室学习Python,并且遇到了华夫饼图的问题。

我有以下字典,我想在华夫饼图中显示它:

import pandas as pd 
import matplotlib.pyplot as plt
from pywaffle import Waffle

dic = {'Xemay':150,'Xedap':20,'Oto':180,'Maybay':80,'Tauthuy':135,'Xelua':5}
df = pd.DataFrame.from_dict(dic, orient='index')

plt.figure(FigureClass=Waffle,rows=5,values=dic,legend={'loc': 'upper left', 'bbox_to_anchor': (1, 1)})
plt.title('Số lượng xe bán được của một công ty')
plt.show()

但是结果出乎意料:

“

相反,图表应该看起来像这样。我在做什么错?

“

python waffle-chart
1个回答
0
投票

为了使Waffle正确显示数据,您需要对数据进行规范化,以使所有值的总和为100。

以下内容对您有用吗?

# Create a dict of normalized data. There are plenty of 
# ways to do this. Here is one approach:
keys = ['Xemay', 'Xedap', 'Oto', 'Maybay', 'Tauthuy', 'Xelua']
vals = np.array([150, 20, 180, 80, 135, 5])
vals = vals/vals.sum()*100
data = dict(zip(keys, vals))

plt.figure(FigureClass=Waffle,
           rows=5,
           values=data,
           legend={'loc': 'upper left', 'bbox_to_anchor': (1, 1.1)})
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.