Fork me on GitHub

pyecharts-8-绘制百分比数据的图形

pyecharts-8-百分比数据绘图

在实际的工作中,我们经常会遇到带有百分比的数据,比如:销售率、利用率等,多种情形下都会产生百分比数据。百分比数据不能直接用于绘图,因为它是字符型的数据,我们必须进行相应的处理才能用于绘图。

本文中介绍的是如何在pyecharts中绘制带有百分比数据的图形。

  • 直接使用百分比数据绘图
  • 使用小数转成百分比数据绘图

导入库

1
2
3
from pyecharts.charts import Line
from pyecharts import options as opts
from pyecharts.commons.utils import JsCode

最主要的库是JsCode,它是用来对输出的格式进行调整

数据

1
2
3
4
data_x = ['202001', '202002', '202003', '202004', '202005', '202006', '202007']
data_y = ['88.51%', '77.11%', '81.67%', '66.61%', '86.74%', '97.55%', '76.18%']
data_y_0 = [float(x.strip('%')) for x in data_y]
data_y_0

绘图

绘图的具体步骤:

  1. 添加x轴数据
  2. 添加y轴数据和标题
  3. 对标签和坐标轴的数据格式进行设置
1
2
3
4
5
6
7
8
9
10
line = (
Line()
.add_xaxis(data_x) # 添加x轴数据
.add_yaxis("月销售率", data_y_0, # 标题和y轴数据
label_opts=opts.LabelOpts(formatter=JsCode("function (params) {return params.value[1] + '%'}")))
.set_global_opts(
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="{value} %"))) # 设置y轴的数据格式
)

line.render_notebook()

案例2-从小数生成百分比

直接从原始数据中生成带有百分比的图形

  • round函数:四舍五入
  • 列表推导式的使用
  • 通过{key:value}直接构造字典数据
  • for循环生成两组数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# encoding: utf-8

from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.globals import ThemeType

def get_data_dict():
# 先生成数据:可以改成连接数据库

# round函数:四舍五入函数
# 使用列表推导式生成两个数据
data_a = [round(n*100,2) for n in [0.2155, 0.423, 0.351, 0.4422, 0.651, 0.722]]
data_b = [round(n*100,2) for n in [0.1233, 0.231, 0.4522, 0.5612, 0.6667, 0.745]]
pdt_list = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
data_dict= {'data':[data_a,data_b], 'head':['商家甲','商家乙'], 'item':pdt_list}
return data_dict

def create_bar(bar_dict):
# 建立百分比的柱状图
bar_item = bar_dict['item'] # ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
bar_head = bar_dict['head'] # ['商家甲','商家乙']
bar_data = bar_dict['data'] # 两个列表中的数据

# 实例化为bar
bar = (
Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
.add_xaxis(bar_item)
.set_global_opts(title_opts=opts.TitleOpts(title="销售情况", subtitle="占比情况"))
)
for i in range(len(bar_head)): # 两个头部元素
bar.add_yaxis(bar_head[i], bar_data[i], label_opts=opts.LabelOpts(formatter="{c} %"))
bar.set_global_opts(
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter="{value} %"), interval=10))
return bar


if __name__=="__main__":
data = get_data_dict()
bar = create_bar(data)
bar.render() # 自动生成的文件

本文标题:pyecharts-8-绘制百分比数据的图形

发布时间:2020年10月14日 - 20:10

原始链接:http://www.renpeter.cn/2020/10/14/pyecharts-8-%E7%BB%98%E5%88%B6%E7%99%BE%E5%88%86%E6%AF%94%E6%95%B0%E6%8D%AE%E7%9A%84%E5%9B%BE%E5%BD%A2.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea