Pyecharts-旭日图

旭日图

先用学院-专业数据练习一下

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import os
import pandas as pd
from pyecharts.charts import Sunburst
from pyecharts import options as opts

df = pd.read_excel('学院-专业.xlsx')

data = []
for college in df['学院'].unique():
# college_dict = {}
# college_dict['name'] = college
college_list = []
college_data = df[df['学院'] == college]

for profession in college_data['专业'].unique():
# profession_dict = {}
# profession_dict['name'] = profession
# profession_dict['value'] = int(college_data[college_data['专业'] == profession]['人数'])
# college_list.append(profession_dict)

profession_dict = opts.SunburstItem(
name=profession,
value=int(college_data[college_data['专业'] == profession]['人数']),
itemstyle_opts=opts.ItemStyleOpts(color=df[df['专业'] == profession]['专业颜色'].unique()[0]),
label_opts=opts.LabelOpts(font_size=int(df[df['专业'] == profession]['专业字体大小'].unique()[0]))
)
college_list.append(profession_dict)

# college_dict['children'] = college_list
college_dict = opts.SunburstItem(
name=college,
children=college_list,
itemstyle_opts=opts.ItemStyleOpts(color=df[df['学院'] == college]['学院颜色'].unique()[0]),
label_opts=opts.LabelOpts(font_size=int(df[df['学院'] == college]['学院字体大小'].unique()[0]))
)
data.append(college_dict)

sunburst = (Sunburst(init_opts=opts.InitOpts(bg_color='white'))
.add('学院和专业',
data,
radius=[0, '95%'],
highlight_policy='ancestor',
sort_='decs',
levels=[
{},
{
'r0': '25%',
'r': '60%',
'itemStyle': {'borderWidth': 2},
# 'label': {'align': 'right'}
},
{
'r0': '60%',
'r': '100%',
'itemStyle': {'borderWidth': 2},
'label': {'fontSize': 10,'align': 'center'}
}
])
.set_global_opts(graphic_opts=[opts.GraphicGroup(graphic_item=opts.GraphicItem(left="45%",top="45%"),
children=[opts.GraphicText(graphic_textstyle_opts=opts.GraphicTextStyleOpts(text='12个学院\n\n22个专业', font="bolder 20px Microsoft YaHei"))])])
)
sunburst.render('sunburst.html')
os.system('sunburst.html')

sun

导入包

1
2
3
4
5
from pyecharts.charts import Sunburst
from pyecharts import options as opts
import os
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot

加载数据

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
data = [
{
"name": "Flora",
"itemStyle": {"color": "#da0d68"},
"children": [
{"name": "Black Tea", "value": 1, "itemStyle": {"color": "#975e6d"}},
{
"name": "Floral",
"itemStyle": {"color": "#e0719c"},
"children": [
{
"name": "Chamomile",
"value": 1,
"itemStyle": {"color": "#f99e1c"},
},
{"name": "Rose", "value": 1, "itemStyle": {"color": "#ef5a78"}},
{"name": "Jasmine", "value": 1, "itemStyle": {"color": "#f7f1bd"}},
],
},
],
},
{
"name": "Fruity",
"itemStyle": {"color": "#da1d23"},
"children": [
{
"name": "Berry",
"itemStyle": {"color": "#dd4c51"},
"children": [
{
"name": "Blackberry",
"value": 1,
"itemStyle": {"color": "#3e0317"},
},
{
"name": "Raspberry",
"value": 1,
"itemStyle": {"color": "#e62969"},
},
{
"name": "Blueberry",
"value": 1,
"itemStyle": {"color": "#6569b0"},
},
{
"name": "Strawberry",
"value": 1,
"itemStyle": {"color": "#ef2d36"},
},
],
},
{
"name": "Dried Fruit",
"itemStyle": {"color": "#c94a44"},
"children": [
{"name": "Raisin", "value": 1, "itemStyle": {"color": "#b53b54"}},
{"name": "Prune", "value": 1, "itemStyle": {"color": "#a5446f"}},
],
},
{
"name": "Other Fruit",
"itemStyle": {"color": "#dd4c51"},
"children": [
{"name": "Coconut", "value": 1, "itemStyle": {"color": "#f2684b"}},
{"name": "Cherry", "value": 1, "itemStyle": {"color": "#e73451"}},
{
"name": "Pomegranate",
"value": 1,
"itemStyle": {"color": "#e65656"},
},
{
"name": "Pineapple",
"value": 1,
"itemStyle": {"color": "#f89a1c"},
},
{"name": "Grape", "value": 1, "itemStyle": {"color": "#aeb92c"}},
{"name": "Apple", "value": 1, "itemStyle": {"color": "#4eb849"}},
{"name": "Peach", "value": 1, "itemStyle": {"color": "#f68a5c"}},
{"name": "Pear", "value": 1, "itemStyle": {"color": "#baa635"}},
],
},
{
"name": "Citrus Fruit",
"itemStyle": {"color": "#f7a128"},
"children": [
{
"name": "Grapefruit",
"value": 1,
"itemStyle": {"color": "#f26355"},
},
{"name": "Orange", "value": 1, "itemStyle": {"color": "#e2631e"}},
{"name": "Lemon", "value": 1, "itemStyle": {"color": "#fde404"}},
{"name": "Lime", "value": 1, "itemStyle": {"color": "#7eb138"}},
],
},
],
},
{
"name": "Sour/\nFermented",
"itemStyle": {"color": "#ebb40f"},
"children": [
{
"name": "Sour",
"itemStyle": {"color": "#e1c315"},
"children": [
{
"name": "Sour Aromatics",
"value": 1,
"itemStyle": {"color": "#9ea718"},
},
{
"name": "Acetic Acid",
"value": 1,
"itemStyle": {"color": "#94a76f"},
},
{
"name": "Butyric Acid",
"value": 1,
"itemStyle": {"color": "#d0b24f"},
},
{
"name": "Isovaleric Acid",
"value": 1,
"itemStyle": {"color": "#8eb646"},
},
{
"name": "Citric Acid",
"value": 1,
"itemStyle": {"color": "#faef07"},
},
{
"name": "Malic Acid",
"value": 1,
"itemStyle": {"color": "#c1ba07"},
},
],
},
{
"name": "Alcohol/\nFremented",
"itemStyle": {"color": "#b09733"},
"children": [
{"name": "Winey", "value": 1, "itemStyle": {"color": "#8f1c53"}},
{"name": "Whiskey", "value": 1, "itemStyle": {"color": "#b34039"}},
{
"name": "Fremented",
"value": 1,
"itemStyle": {"color": "#ba9232"},
},
{"name": "Overripe", "value": 1, "itemStyle": {"color": "#8b6439"}},
],
},
],
},
{
"name": "Green/\nVegetative",
"itemStyle": {"color": "#187a2f"},
"children": [
{"name": "Olive Oil", "value": 1, "itemStyle": {"color": "#a2b029"}},
{"name": "Raw", "value": 1, "itemStyle": {"color": "#718933"}},
{
"name": "Green/\nVegetative",
"itemStyle": {"color": "#3aa255"},
"children": [
{
"name": "Under-ripe",
"value": 1,
"itemStyle": {"color": "#a2bb2b"},
},
{"name": "Peapod", "value": 1, "itemStyle": {"color": "#62aa3c"}},
{"name": "Fresh", "value": 1, "itemStyle": {"color": "#03a653"}},
{
"name": "Dark Green",
"value": 1,
"itemStyle": {"color": "#038549"},
},
{
"name": "Vegetative",
"value": 1,
"itemStyle": {"color": "#28b44b"},
},
{"name": "Hay-like", "value": 1, "itemStyle": {"color": "#a3a830"}},
{
"name": "Herb-like",
"value": 1,
"itemStyle": {"color": "#7ac141"},
},
],
},
{"name": "Beany", "value": 1, "itemStyle": {"color": "#5e9a80"}},
],
},
{
"name": "Other",
"itemStyle": {"color": "#0aa3b5"},
"children": [
{
"name": "Papery/Musty",
"itemStyle": {"color": "#9db2b7"},
"children": [
{"name": "Stale", "value": 1, "itemStyle": {"color": "#8b8c90"}},
{
"name": "Cardboard",
"value": 1,
"itemStyle": {"color": "#beb276"},
},
{"name": "Papery", "value": 1, "itemStyle": {"color": "#fefef4"}},
{"name": "Woody", "value": 1, "itemStyle": {"color": "#744e03"}},
{
"name": "Moldy/Damp",
"value": 1,
"itemStyle": {"color": "#a3a36f"},
},
{
"name": "Musty/Dusty",
"value": 1,
"itemStyle": {"color": "#c9b583"},
},
{
"name": "Musty/Earthy",
"value": 1,
"itemStyle": {"color": "#978847"},
},
{"name": "Animalic", "value": 1, "itemStyle": {"color": "#9d977f"}},
{
"name": "Meaty Brothy",
"value": 1,
"itemStyle": {"color": "#cc7b6a"},
},
{"name": "Phenolic", "value": 1, "itemStyle": {"color": "#db646a"}},
],
},
{
"name": "Chemical",
"itemStyle": {"color": "#76c0cb"},
"children": [
{"name": "Bitter", "value": 1, "itemStyle": {"color": "#80a89d"}},
{"name": "Salty", "value": 1, "itemStyle": {"color": "#def2fd"}},
{
"name": "Medicinal",
"value": 1,
"itemStyle": {"color": "#7a9bae"},
},
{
"name": "Petroleum",
"value": 1,
"itemStyle": {"color": "#039fb8"},
},
{"name": "Skunky", "value": 1, "itemStyle": {"color": "#5e777b"}},
{"name": "Rubber", "value": 1, "itemStyle": {"color": "#120c0c"}},
],
},
],
},
{
"name": "Roasted",
"itemStyle": {"color": "#c94930"},
"children": [
{"name": "Pipe Tobacco", "value": 1, "itemStyle": {"color": "#caa465"}},
{"name": "Tobacco", "value": 1, "itemStyle": {"color": "#dfbd7e"}},
{
"name": "Burnt",
"itemStyle": {"color": "#be8663"},
"children": [
{"name": "Acrid", "value": 1, "itemStyle": {"color": "#b9a449"}},
{"name": "Ashy", "value": 1, "itemStyle": {"color": "#899893"}},
{"name": "Smoky", "value": 1, "itemStyle": {"color": "#a1743b"}},
{
"name": "Brown, Roast",
"value": 1,
"itemStyle": {"color": "#894810"},
},
],
},
{
"name": "Cereal",
"itemStyle": {"color": "#ddaf61"},
"children": [
{"name": "Grain", "value": 1, "itemStyle": {"color": "#b7906f"}},
{"name": "Malt", "value": 1, "itemStyle": {"color": "#eb9d5f"}},
],
},
],
},
{
"name": "Spices",
"itemStyle": {"color": "#ad213e"},
"children": [
{"name": "Pungent", "value": 1, "itemStyle": {"color": "#794752"}},
{"name": "Pepper", "value": 1, "itemStyle": {"color": "#cc3d41"}},
{
"name": "Brown Spice",
"itemStyle": {"color": "#b14d57"},
"children": [
{"name": "Anise", "value": 1, "itemStyle": {"color": "#c78936"}},
{"name": "Nutmeg", "value": 1, "itemStyle": {"color": "#8c292c"}},
{"name": "Cinnamon", "value": 1, "itemStyle": {"color": "#e5762e"}},
{"name": "Clove", "value": 1, "itemStyle": {"color": "#a16c5a"}},
],
},
],
},
{
"name": "Nutty/\nCocoa",
"itemStyle": {"color": "#a87b64"},
"children": [
{
"name": "Nutty",
"itemStyle": {"color": "#c78869"},
"children": [
{"name": "Peanuts", "value": 1, "itemStyle": {"color": "#d4ad12"}},
{"name": "Hazelnut", "value": 1, "itemStyle": {"color": "#9d5433"}},
{"name": "Almond", "value": 1, "itemStyle": {"color": "#c89f83"}},
],
},
{
"name": "Cocoa",
"itemStyle": {"color": "#bb764c"},
"children": [
{
"name": "Chocolate",
"value": 1,
"itemStyle": {"color": "#692a19"},
},
{
"name": "Dark Chocolate",
"value": 1,
"itemStyle": {"color": "#470604"},
},
],
},
],
},
{
"name": "Sweet",
"itemStyle": {"color": "#e65832"},
"children": [
{
"name": "Brown Sugar",
"itemStyle": {"color": "#d45a59"},
"children": [
{"name": "Molasses", "value": 1, "itemStyle": {"color": "#310d0f"}},
{
"name": "Maple Syrup",
"value": 1,
"itemStyle": {"color": "#ae341f"},
},
{
"name": "Caramelized",
"value": 1,
"itemStyle": {"color": "#d78823"},
},
{"name": "Honey", "value": 1, "itemStyle": {"color": "#da5c1f"}},
],
},
{"name": "Vanilla", "value": 1, "itemStyle": {"color": "#f89a80"}},
{"name": "Vanillin", "value": 1, "itemStyle": {"color": "#f37674"}},
{"name": "Overall Sweet", "value": 1, "itemStyle": {"color": "#e75b68"}},
{"name": "Sweet Aromatics", "value": 1, "itemStyle": {"color": "#d0545f"}},
],
},
]

唉,用pyecharts画旭日图太依赖这样的数据结构了,或许我们大多数人都很少用到这样的结构,在实用中我们通常用excel存储数据,类似这样

graph

要改为合适的数据格式,可能需要编程做数据处理了,这里提供一种思路,可以筛选出第一级某标签对应的数据,再添加属性,再筛选二级标题下的数据,再添加属性,以此类推。这里我们主要以画图为主,先用json数据处理。

开始画图

1
2
3
4
5
6
sun = (Sunburst()
.add("", data_pair=data)

)
sun.render("旭日图.html")
os.system("旭日图.html")

添加元素

1
2
3
4
5
6
7
sun = (Sunburst(init_opts=opts.InitOpts(width="900px", height="600px"))
.add("", data_pair=data,
highlight_policy="ancestor", # 高亮相关的扇形块
radius=[0, "95%"], # 数组的第一项是内半径,第二项是外半径。
sort_="null", # 排序方式)
.set_global_opts(title_opts=opts.TitleOpts(title="饮料风味旭日图"))
)

sort_可选’descendant’:高亮该扇形块和后代元素,其他元素将被淡化;

​ ‘ancestor’:高亮该扇形块和祖先元素;

​ ‘self’:只高亮自身;

​ ‘none’:不会淡化其他元素。

设置层级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
levels=[
{},
{
"r0": "15%", # 第一层内半径
"r": "35%", # 第一层外半径,100%是到达画框边界
"itemStyle": {"borderWidth": 2}, # 边框宽度
"label": {"rotate": 'tangential'}, # 标签旋转角度,这里表示全按切线方向,一定还有其他选项,目前没找全。radial-径向;tangential-切向
},
{"r0": "35%", "r": "70%", "label": {"align": "right"}}, # 对齐方式
{
"r0": "70%",
"r": "72%",
"label": {"position": "outside", "padding": 3, "silent": False}, # padding 内边距;不需要使用Fundebug为True
"itemStyle": {"borderWidth": 3},
},
]

网上没有搜到详细的教程,感觉可能是CSS代码,可能触及到知识的边缘了。

大功告成!

Pyecharts-气泡图

气泡图

气泡图

导入所需要的包

1
2
3
4
5
import numpy as np
import pandas as pd
from pyecharts.commons.utils import JsCode
from pyecharts.charts import *
from pyecharts import options as opts

读取数据

1
2
df1 = pd.read_excel("气泡图数据.xlsx", sheet_name=0, header=0)
df2 = pd.read_excel("气泡图数据.xlsx", sheet_name=1, header=0)

数据处理

1
2
3
4
5
6
7
data1 = []
for y, s, c in zip(df1['人均寿命'], df1['GDP总量'], df1['国家']):
data1.append([y, s, c])

data2 = []
for y, s, c in zip(df2['人均寿命'], df2['GDP总量'], df2['国家']):
data2.append([y, s, c])

另一种处理数据的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
data1 = []
for n, x, y, s in zip(df1['国家'], df1['人均GDP'], df1['人均寿命'], df1['GDP总量']):
data1.append(opts.ScatterItem(
name=n,
value=[x, y],
symbol_size=math.sqrt(s)/500
))

data2 = []
for n, x, y, s in zip(df2['国家'], df2['人均GDP'], df2['人均寿命'], df2['GDP总量']):
data2.append(opts.ScatterItem(
name=n,
value=[x, y],
symbol_size=math.sqrt(s)/500
))

这样同时映射了图形大小,感觉这样更好点。

先画1990年

1
2
3
4
5
6
7
8
scatter1 = (Scatter()
.add_xaxis(df1['人均GDP'])
.add_yaxis('1990',
data1)
.set_global_opts(xaxis_opts=opts.AxisOpts(type_='value'),
yaxis_opts=opts.AxisOpts(is_scale=True))
)
scatter1.render("气泡图.html")

JsCode()

可以用以下代码来看参数怎么传递

1
item_color_js_2 = """function(x) {console.log(x); return x;}"""

映射GDP总量为不同大小

1
2
3
4
5
size = '''function(x) {return Math.sqrt(x[2])/500}'''

.add_yaxis('1990',
data1,
symbol_size=JsCode(size))

设置tooltips

1
2
3
4
5
6
tool = '''function(x) {return x.seriesName + '-' + x.data[3] + '<br/>'
+'人均GDP: '+x.data[0]+' 美元<br/>'
+'GDP总量: '+x.data[2]+' 美元<br/>'
+'人均寿命: '+x.data[1]+'岁';}'''

.set_global_opts(tooltip_opts=opts.TooltipOpts(formatter=JsCode(tool)))

再画2015年

1
2
3
4
5
6
7
8
9
10
scatter2 = (Scatter()
.add_xaxis(df2['人均GDP'])
.add_yaxis('2015',
data2,
symbol_size=JsCode(size))
)

scatter1.overlap(scatter2)
scatter1.render('气泡图.html')
os.system('气泡图.html')

设置颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
item_color_js_1 = """new echarts.graphic.RadialGradient(0.4, 0.3, 1, [{
offset: 0,
color: 'rgb(251, 118, 123)'
}, {
offset: 1,
color: 'rgb(204, 46, 72)'
}])"""

item_color_js_2 = """new echarts.graphic.RadialGradient(0.4, 0.3, 1, [{
offset: 0,
color: 'rgb(129, 227, 238)'
}, {
offset: 1,
color: 'rgb(25, 183, 207)'
}])"""

echarts.graphic.RadialGradient:径向渐变色设置,前三个参数分别是圆心 x, y 和半径,第四个参数是数组, 用于配置颜色的渐变过程. 每一项为一个对象, 包含offset和color两个参数. offset的范围是0 ~ 1, 用于表示位置(offset: 0表示0% 处的颜色;offset: 1表示100% 处的颜色)

1
2
3
4
# scatter1设置
.add_yaxis(itemstyle_opts=opts.ItemStyleOpts(color=JsCode(item_color_js_1)))
# scatter2设置
.add_yaxis(itemstyle_opts=opts.ItemStyleOpts(color=JsCode(item_color_js_2)))

去掉标签

1
.add_yaxis(label_opts=opts.LabelOpts(is_show=False))

设置坐标轴

1
2
.set_global_opts(xaxis_opts=opts.AxisOpts(type_='value', name='人均GDP'),
yaxis_opts=opts.AxisOpts(is_scale=True, name='人均寿命'),

坐标轴类型: ‘value’-连续数据;'category '-离散数据;‘time’-时间轴;‘log’-对数轴

设置阴影

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
item_style_1 = {
'shadowBlur': 10,
'shadowColor': 'rgba(120, 36, 50, 0.5)',
'shadowOffsetY': 5,
'color': JsCode(item_color_js_1)
}

item_style_2 = {
'shadowBlur': 10,
'shadowColor': 'rgba(120, 36, 50, 0.5)',
'shadowOffsetY': 5,
'color': JsCode(item_color_js_2)
}

scatter1 = (Scatter()
.add_xaxis(df1['人均GDP'])
.add_yaxis('1990',
data1,
symbol_size=JsCode(size),
itemstyle_opts=item_style_1)
.set_global_opts(xaxis_opts=opts.AxisOpts(type_='value'),
yaxis_opts=opts.AxisOpts(is_scale=True),
tooltip_opts=opts.TooltipOpts(formatter=JsCode(tool)))
)
scatter2 = (Scatter()
.add_xaxis(df2['人均GDP'])
.add_yaxis('2015',
data2,
symbol_size=JsCode(size),
itemstyle_opts=item_style_2)
)

设置背景颜色、大小

1
2
3
4
5
6
7
8
9
bg_color_js = """new echarts.graphic.RadialGradient(0.3, 0.3, 0.8, [{
offset: 0,
color: '#f7f8fa'
}, {
offset: 1,
color: '#cdd0d5'
}])"""

Scatter(init_opts=opts.InitOpts(bg_color=JsCode(bg_color_js), width='1000px', height='800px'))

设置分割线

1
2
3
.set_global_opts(xaxis_opts=opts.AxisOpts(type_='value', name='人均GDP', splitline_opts=opts.SplitLineOpts(is_show=True,linestyle_opts=opts.LineStyleOpts(type_='dashed'))),
yaxis_opts=opts.AxisOpts(is_scale=True, name='人均寿命', splitline_opts=opts.SplitLineOpts(is_show=True,linestyle_opts=opts.LineStyleOpts(type_='dashed'))),
tooltip_opts=opts.TooltipOpts(formatter=JsCode(tool)))

添加标题、图例位置

.set_global_opts中插入

1
2
legend_opts=opts.LegendOpts(is_show=True, pos_right=10),
title_opts=opts.TitleOpts(title="1990 与 2015 年各国家人均寿命与 GDP")

全代码

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
import numpy as np
import pandas as pd
from pyecharts.commons.utils import JsCode
from pyecharts.charts import *
from pyecharts import options as opts

df1 = pd.read_excel("气泡图数据.xlsx", sheet_name=0, header=0)
df2 = pd.read_excel("气泡图数据.xlsx", sheet_name=1, header=0)

data1 = []
for y, s, c in zip(df1['人均寿命'], df1['GDP总量'], df1['国家']):
data1.append([y, s, c])

data2 = []
for y, s, c in zip(df2['人均寿命'], df2['GDP总量'], df2['国家']):
data2.append([y, s, c])


size = '''function(x) {return Math.sqrt(x[2])/500}'''

tool = '''function(x) {return x.seriesName + '-' + x.data[3] + '<br/>'
+'人均GDP: '+x.data[0]+' 美元<br/>'
+'GDP总量: '+x.data[2]+' 美元<br/>'
+'人均寿命: '+x.data[1]+'岁';}'''

item_color_js_1 = """new echarts.graphic.RadialGradient(0.4, 0.3, 1, [{
offset: 0,
color: 'rgb(251, 118, 123)'
}, {
offset: 1,
color: 'rgb(204, 46, 72)'
}])"""

item_color_js_2 = """new echarts.graphic.RadialGradient(0.4, 0.3, 1, [{
offset: 0,
color: 'rgb(129, 227, 238)'
}, {
offset: 1,
color: 'rgb(25, 183, 207)'
}])"""
item_style_1 = {
'shadowBlur': 10,
'shadowColor': 'rgba(120, 36, 50, 0.5)',
'shadowOffsetY': 5,
'color': JsCode(item_color_js_1)
}

item_style_2 = {
'shadowBlur': 10,
'shadowColor': 'rgba(120, 36, 50, 0.5)',
'shadowOffsetY': 5,
'color': JsCode(item_color_js_2)
}

bg_color_js = '''new echarts.graphic.RadialGradient(0.3, 0.3, 0.8, [
{
offset: 0,
color: '#f7f8fa'
},
{
offset: 1,
color: '#cdd0d5'
}
])'''

scatter1 = (Scatter(init_opts=opts.InitOpts(bg_color=JsCode(bg_color_js), width='750px', height='600px'))
.add_xaxis(df1['人均GDP'])
.add_yaxis('1990',
data1,
symbol_size=JsCode(size),
label_opts=opts.LabelOpts(is_show=False),
itemstyle_opts=item_style_1)
.set_global_opts(xaxis_opts=opts.AxisOpts(type_='value', name='人均GDP',
splitline_opts=opts.SplitLineOpts(is_show=True,
linestyle_opts=opts.LineStyleOpts(type_='dashed'))),
yaxis_opts=opts.AxisOpts(is_scale=True, name='人均寿命',
splitline_opts=opts.SplitLineOpts(is_show=True,
linestyle_opts=opts.LineStyleOpts(type_='dashed'))),
tooltip_opts=opts.TooltipOpts(formatter=JsCode(tool)),
legend_opts=opts.LegendOpts(is_show=True, pos_right=10),
title_opts=opts.TitleOpts(title="1990 与 2015 年各国家人均寿命与 GDP"))
)
scatter2 = (Scatter()
.add_xaxis(df2['人均GDP'])
.add_yaxis('2015',
data2,
symbol_size=JsCode(size),
label_opts=opts.LabelOpts(is_show=False),
itemstyle_opts=item_style_2)
)

scatter1.overlap(scatter2)
scatter1.render('气泡图.html')
os.system('气泡图.html')

大功告成!

Pyecharts-关系图

关系图

先用转专业数据练习一下

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
41
42
43
44
45
46
47
48
49
50
import pandas as pd
import os
from pyecharts.charts import Graph
from pyecharts import options as opts

df: pd.DataFrame = pd.read_excel(r'山西大学2021年本科生转专业情况.xlsx')
node_list = [
{'name': '建筑电气与智能化', 'symbolSize': 29, 'category': '其他情况'},
{'name': '能源与动力工程', 'symbolSize': 22, 'category': '成绩优秀'},
{'name': '环境科学与工程类', 'symbolSize': 15, 'category': '成绩优秀'},
{'name': '建筑环境与能源应用工程', 'symbolSize': 16, 'category': '成绩优秀'},
{'name': '机械电子工程', 'symbolSize': 10, 'category': '成绩优秀'},
{'name': '生物科学类', 'symbolSize': 10, 'category': '成绩优秀'},
{'name': '工商管理类', 'symbolSize': 8, 'category': '成绩优秀'},
{'name': '化学类', 'symbolSize': 8, 'category': '成绩优秀'},
{'name': '电气工程及其自动化', 'symbolSize': 48, 'category': '成绩优秀'},
{'name': '计算机科学与技术', 'symbolSize': 15, 'category': '成绩优秀'},
{'name': '电子信息工程', 'symbolSize': 11, 'category': '成绩优秀'},
{'name': '数据科学与大数据技术', 'symbolSize': 8, 'category': '成绩优秀'},
{'name': '经济学类', 'symbolSize': 8, 'category': '成绩优秀'}
]

df1: pd.DataFrame = df[['转出专业', '转入专业']]
df1 = df1.drop_duplicates()
df1.columns = ['source', 'target']
link_list = []
for i in range(len(df1)):
dict = {'source': df1.iloc[i, 0],
'target': df1.iloc[i, 1]}
link_list.append(dict)
# print(link_list)

categories = [
{"name": '成绩优秀'},
{"name": '其他情况'},
]

G = (Graph()
.add(series_name="悲惨世界人物关系图",
nodes=node_list,
links=link_list,
categories=categories,
layout="circular",
is_rotate_label=True,
linestyle_opts=opts.LineStyleOpts(color="source", curve=0.3, opacity=0.7))
.set_global_opts(title_opts=opts.TitleOpts(title="悲惨世界人物关系图"),
legend_opts=opts.LegendOpts(orient="vertical", pos_left="2%", pos_top="20%"))
)
G.render("graph.html")
os.system("graph.html")

导入包

1
2
3
4
import os
import json
from pyecharts.charts import Graph
from pyecharts import options as opts

准备数据

这里我们使用“悲惨世界”人物关系的数据,数据来源:https://echarts.apache.org/examples/data/asset/data/les-miserables.json

这是一个json数据,我们先把它拷贝在本地同一文件夹下。

读取

1
2
3
4
with open(r'D:\Pycharm\myproject\Pyecharts\关系图\les-miserables.json', "r") as f:
data = json.load(f)

print(data)

这里with open()函数是用来读取文件的。我们一般读取文件时要先f.open(),在判断打开是否成功,成功则继续读取,否则显示错误提示。读完后我们还需f.close()。为了简化代码,python使用这个函数可以大大简化代码长度,简洁明了。

open()中第一个参数是路径,我们一般复制过来的路径是右斜杠,采用r""可以直接使用,不使用r则需要把右斜杠转为左斜杠。“r”代表只读。

数据处理

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
nodes = []
idDict = dict()
for node in data["nodes"]:
nodes.append(
{
"x": node["x"],
"y": node["y"],
"name": node["name"],
"symbolSize": node["symbolSize"],
"category": node["category"]
}
)
idDict[node["id"]] = node["name"]

link = [
{
"source": idDict[i["source"]],
"target": idDict[i["target"]]
}
for i in data["links"]
]

categories = [
{
"name": i["name"]
}
for i in data["categories"]
]

把json数据里的三类数据(点、连线、类别)分别读取到nodes、link、categories里。

开始画图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
G = (Graph(init_opts=opts.InitOpts(width="900px", height="900px"))
.add(series_name="悲惨世界人物关系图",
nodes=nodes,
links=link,
categories=categories,
layout="circular",
is_rotate_label=True,
linestyle_opts=opts.LineStyleOpts(color="source", curve=0.3, opacity=0.7))
.set_global_opts(title_opts=opts.TitleOpts(title="悲惨世界人物关系图"),
legend_opts=opts.LegendOpts(orient="vertical", pos_left="2%", pos_top="20%"))
)

# G.render("graph.html")
# os.system("graph.html")

make_snapshot(snapshot, G.render("graph.html"), "graph.png") # 渲染图片

后来又摸索出一种方法

我准备了excel数据,这里我使用了这个网站(JSON转Excel - UU在线工具 (uutool.cn))把json数据保存为excel数据,因为我们一般准备的数据是excel数据,导入后使用to_json()把dataframe转为json数据,之后再做处理。

1
2
3
4
5
data = pd.read_excel(r"node.xlsx")
nodes = eval(data.to_json(orient="records", force_ascii=False))
print(nodes)
data1 = pd.read_excel(r"link.xlsx")
link = eval(data1.to_json(orient="records", force_ascii=False))

这里to_json()函数里orient参数详见https://blog.csdn.net/qq_41780234/article/details/84990551

注意这里转换完的json数据是字符串格式,需要eval()函数去掉两边的引号,转为list格式。

1
2
3
4
5
6
7
8
9
10
links = [
{
"source": nodes[i["source"]]["name"],
"target": nodes[i["target"]]["name"]
}
for i in link
]
# print(links)
categories = [{"name": "A"}, {"name": "B"}, {"name": "C"}, {"name": "D"}, {"name": "E"},
{"name": "F"}, {"name": "G"}, {"name": "H"}, {"name": "I"}]

这是对link数据的处理。

接下来画图的代码就和上面一样啦!

大功告成!

Pyecharts-饼图

饼图

饼图

导入包

1
2
3
4
5
6
import os
from pyecharts.globals import ThemeType
from pyecharts.charts import Pie
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot

加载数据

1
2
3
4
attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [11, 12, 13, 10, 10, 10]

print(list(zip(attr, v1)))

这里zip()将对象打包成一个元组,list()转为列表

另外一种处理数据的方法:

1
2
3
4
5
6
7
data_pair = []
for x, y, c in zip(attr, v1, ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']):
data_pair.append(opts.PieItem(
name=x,
value=y,
itemstyle_opts=opts.ItemStyleOpts(color=c)
))

开始做图

1
2
3
4
5
6
7
8
9
pie = (Pie(init_opts=opts.InitOpts(theme=ThemeType.MACARONS))
.add("服装", list(zip(attr, v1)), # 用第二种方法时,数据位置改为data_pair
radius=[40, 200],
rosetype="radius",
is_clockwise=True)
)

pie.render("饼图.html")
os.system("饼图.html")

添加标题

1
.set_global_opts(title_opts=opts.TitleOpts("服装销量", pos_left="10%"))

图例位置

1
.set_global_opts(legend_opts=opts.LegendOpts(pos_right="10%", orient="vertical"))

设置颜色

1
.set_colors(["#5470c6", "#91cc75"," #fac858", "#ee6666", "#73c0de", "#3ba272", "#fc8452", "#9a60b4"])

使用第二种方法时,不需要设置颜色,因为数据中包含了颜色

渲染图片

1
make_snapshot(snapshot, pie.render(), "饼图.png")

大功告成!

Pyecharts-柱状图

柱状图

bar

导入包

1
2
3
4
5
import os
from pyecharts.charts import Bar
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_phantomjs import snapshot

数据准备

1
2
3
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.8, 48.7, 18.8, 6.0, 2.3]

v1是蒸发量,v2是降水量

简单构图

1
2
3
4
5
6
7
bar = (Bar()
.add_xaxis(month)
.add_yaxis("蒸发量", v1)
.add_yaxis("降水量", v2)
)
bar.render("柱形图.html")
os.system("柱形图.html")

添加标记线、标记点

1
.set_series_opts(markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(name="平均值", type_='average')]))

注意:这里data是一个列表,里面放着不同位置的标记线。

1
2
3
4
set_series_opts(markpoint_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(name="最大值", type_="max"), 
opts.MarkLineItem(name="最小值", type_="min")],
symbol_size=55,
label_opts=opts.LabelOpts(position="inside", color="#fff")),

去掉标签

1
set_series_opts(label_opts=opts.LabelOpts(is_show=False))

交换xy轴

1
.reversal_axis()

设置图例标题

1
2
set_global_opts(title_opts=opts.TitleOpts("全年蒸发量与降雨量", pos_left="center"),
legend_opts=opts.LegendOpts(pos_right="10%", pos_top="40", orient="vertical"))

添加坐标轴标签

1
2
set_global_opts(xaxis_opts=opts.AxisOpts(name="月份"),
yaxis_opts=opts.AxisOpts(name="蒸发量与降雨量"))

设置背景

1
Bar(init_opts=opts.InitOpts(bg_color="white")

渲染图片

  • 下载Download PhantomJS

  • phantomjs.exe所在的bin目录加入到环境变量(路径无中文)。配置成功后,可以在命令行下测试一下,输入:phantomjs,如果可以进入到PhantomJS的命令行,那么就证明配置完成了。

  • pip install snapshot-phantomjs

  • phantomjs.exe复制到:C:\Users\你的名字\AppData\Local\Microsoft\WindowsApps

1
make_snapshot(snapshot, bar.render(), "bar.png")

大功告成!

Hello World

哇哦!打开新世界的大门了!😍

做网站的初衷大概是太闲,想玩玩。

又或许曾经想做一名程序员,毕竟做网站是一名程序员基本的技能嘛。

所以就来试试。

想着在茫茫的网络中找到一块属于自己的净土,这里没有市井中的流量,没有万众瞩目下的喧嚣,嘿嘿,只有我一个人躲在网络的边缘享受属于自己的安静。没事的时候就和自己聊聊,反正没人听到😝(不想让听到的当然不会写这里啦)

当然还有一个刚需,就是想找一个类似云笔记软件,不用每天搬砖(重重的书包),走哪只要有网都可以看。看了市面上所有的软件,没有心仪的,要么付费,要么有限制,要么要下一大堆的app(内存预警)。思来想去,还是网站最适合我,只要像名字一样记住网址,四海之下,足迹天涯,只要有网,就能用。我始终感觉,未来互联网的发展趋势就应该成为这样,摆脱了手机,摆脱了电脑,未来走到哪都是屏幕,你只需要登陆自己的网站,随时办公,随时学习,这才叫真正的解放生产力😂

害,扯远啦。

To live is to change the world!

  • Copyrights © 2022-2023 发现美的眼睛
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信