如何用字典创建华夫饼图?

时间:2020-01-10 10:35:13

标签: python waffle-chart

我正在通过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()

但是结果出乎意料:

Screenshot1

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

Screenshot2

2 个答案:

答案 0 :(得分:3)

实际上,您的代码是正确的,并且Waffle可以正确显示您的数据(放大您的绘图以查看正方形...)

但是,要获得所需的输出,您必须使用参数“ rows”和“ columns”,它们指定了华夫饼图的尺寸。

nRows=5
countsPerBlock=10  # 1 block = 10 counts
plt.figure(FigureClass=Waffle,
           rows=nRows,
           columns=int(np.ceil(sum(dic.values())/nRows/countsPerBlock)),
           values=dic,
           legend={'loc': 'upper left', 'bbox_to_anchor': (1, 1.1)})
plt.show()

Screenshot solution 2

请注意,华夫饼在内部应用了一些舍入(请参阅参数rounding_rule),这就是countsPerBlock并非完全正确的原因,除非您自己缩放数据。要完全重现所需的输出,请使用以下代码:

nRows = 5
countsPerBlock = 10
keys = ['Xemay', 'Xedap', 'Oto', 'Maybay', 'Tauthuy', 'Xelua']
vals = np.array([150, 20, 180, 80, 135, 5])
vals = np.ceil(vals/countsPerBlock)
data = dict(zip(keys, vals))

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

Screenshot solution final

或者,您可以对数据进行规范化,以使值的总和为100。在5x20的正方形中,一个正方形代表数据的1%。

# 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))
nRows = 5
# ...

Screenshot solution final

答案 1 :(得分:0)

这两个代码选项可以解决我的问题:

1。诺曼纽斯先生的贡献:

nRows = 5
countsPerBlock = 10
keys = ['Xemay', 'Xedap', 'Oto', 'Maybay', 'Tauthuy', 'Xelua']
vals = np.array([150, 20, 180, 80, 135, 5])
vals = np.ceil(vals/countsPerBlock)
data = dict(zip(keys, vals))

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

2。从我学到的东西:

fig = plt.figure(
    FigureClass=Waffle, 
    rows=5, 
    values=df[0]/10, 
    title={'label': 'So luong xe duoc ban cua mot cong ty', 'loc': 'left'},
    labels=df.index.tolist(),
    legend={'loc': 'lower right', 'bbox_to_anchor': (1, 0.5)}
)
plt.show()

结果如下: enter image description here