IT journey (ID: Jake_Internet) please contact authorization (wechat ID: Hc220088)

These interactive charts made by Pyecharts are absolutely stunning!

Introduction and installation of Pyecharts

1, the introduction of

Echarts is an open source data visualization by Baidu, with good interaction, exquisite chart design, has been recognized by many developers. Python, on the other hand, is an expressive language that is well suited for data processing. When data analysis meets data visualization, Pyecharts was born.

  • Simple API design, silky smooth use, support chain call
  • It contains over 30 common charts, and you can find everything
  • Support mainstream Notebook environment, Jupyter Notebook and JupyterLab
  • Easy to integrate into Flask, Sanic, Django and other major Web frameworks
  • Highly flexible configuration items can be easily matched to create beautiful charts
  • Detailed documentation and examples to help developers get started faster
  • Up to 400+ map files, and support native Baidu map, provide strong support for geographic data visualization

The Pyecharts version v0.5.x is incompatible with v1, which is a completely new version and has a very different syntax.

2, installation,

Install pyecharts

pip install pyecharts -i http://pypi.douban.com/simple --trusted-host pypi.douban.com import pyecharts Print (pyecharts.__version__) # Check the pyecharts versionCopy the code

Install the relevant map extension packs

PIP install -i https://pypi.tuna.tsinghua.edu.cn/simple echarts - countries - pypkg # global map PIP install - I https://pypi.tuna.tsinghua.edu.cn/simple echarts - China - provinces - pypkg # Chinese provincial map of PIP install - I https://pypi.tuna.tsinghua.edu.cn/simple echarts - China - cities - pypkg # map of China municipal PIP install - I https://pypi.tuna.tsinghua.edu.cn/simple echarts - China - counties - pypkg # county district of China mapCopy the code

Second, draw geographical charts

1. World map — Data visualization

According to the data in Starbucks. CSV, the number of stores corresponding to each Country was firstly calculated, and the world map was used to represent the global distribution of Starbucks front stores.

import pandas as pd from pyecharts.charts import Map from pyecharts import options as opts from pyecharts.globals import  ThemeType, ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/ pd.read_csv("Starbucks.csv")['Country'] data = df.value_counts() datas = [(i, int(j)) for i, j in zip(data.index, Map_ = Map(init_opts= opts.initopts (theme= themetype.purple_passion)) # add(" number of stores ", data_pair=datas, Maptype ="world") map.set_series_opts (label_opts= opts.labelopts (is_show=False)) Title_opts = opts.titleopts (title=" Starbucks stores worldwide ", pos_left='40%', pos_top='10'), Legend_opts =opts.LegendOpts(is_show=False), visualMap_opts =opts.VisualMapOpts(max_=13608, min_=1) Is_piecewise = True, pieces = [{9, "Max" : "min" : 1, "label" : "1-9", "color" : "# 00 FFFF"}, {# section to add legend comments and color "Max" : 99, "min" : 10, "label": "10-99", "color": "#A52A2A"}, {"max": 499, "min": 100, "label": "100-499", "color": "#0000FF "}, {"max": 999, "min": 500, "label": "500-999", "color": "#FF00FF"}, {"max": 2000, "min": 1000, "label": "1000-2000", "color": "#228B22"}, {"max": 3000, "min": 2000, "label": "2000-3000", "color": "#FF0000"}, {"max": 20000, "min": 10000, "label": ">=10000", "color": "#FFD700"}])) # render map_.render(' Starbucks stores around the world ')Copy the code

The running effect is as follows:

2. Country map — data visualization

Scatter plot of ripples

Using the data in China. CSV, firstly calculate the number of stores in each City, and then use the Geo module in Pyecharts package to draw the ripple scatter map of Starbucks storefront stores in China.

import pandas as pd from pyecharts.globals import ThemeType, CurrentConfig, GeoType from pyecharts import options as opts from pyecharts.charts import Geo CurrentConfig.ONLINE_HOST = Df = pd.read_csv("china.csv")['City'] data = df.value_counts() datas = [(i, int(j)) for i, j in zip(data.index, data.values)] print(datas) geo = Geo(init_opts=opts.InitOpts(width='1000px', height='600px', theme=ThemeType.DARK)) geo.add_schema(maptype='china', Label_opts = opts.labelopts (is_show=True) # geo. Add (data_pair=datas, type_=GeoType.EFFECT_SCATTER, symbol_size=8) geo.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) Geo-set_global_opts (title_opts= opts.titLeopts (title_opts= opts.titLeopts (title_opts= opts.titLeopts (title_opts= opts.titLeopts), visualMap_opts = opts.visualMapopts (max_=550, Is_piecewise = True, pieces = [{50, "Max" : "min" : 0, "label" : "0 to 50", "color" : "# 708090"}, {# section to add legend comments and color "Max" : 100, "min": 51, "label": "51-100", "color": "#00FFFF"}, {"max": 200, "min": 101, "label": "101-200", "color": "#00008B"}, {"max": 300, "min": 201, "label": "201-300", "color": "#8B008B"}, {"max": 600, "min": 500, "label": "500-600", "color" : "# FF0000"})) geo. Render (" starbucks stores distribution in China. The HTML ")Copy the code

The running effect is as follows:

Dynamic trajectory diagram

from pyecharts import options as opts from pyecharts.charts import Geo from pyecharts.globals import ChartType, SymbolType, CurrentConfig currentconfig. ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' maptype="china", itemstyle_opts=opts.ItemStyleOpts(color="#323c48", border_color="#111"), Label_opts = opts. LabelOpts (is_show = True)), add (" ", [(" guangzhou ", 55), (" Beijing ", 66), (" hangzhou ", 77), (" chongqing ", 88), (' chengdu, 100), (' haikou ', 80)], type_ = ChartType. EFFECT_SCATTER, color = "white"). The add (" ", [(" guangzhou ", "Shanghai"), (" guangzhou ", "Beijing"), (" guangzhou ", "hangzhou"), (" guangzhou ", "chongqing"), (' chengdu ', 'haikou'), (' haikou ', 'Beijing'), (' haikou ', 'chongqing), (' chongqing', 'Shanghai')], type_ = ChartType. LINES, effect_opts=opts.EffectOpts( symbol=SymbolType.ARROW, symbol_size=6, color="blue" ), Linestyle_opts = opts. LineStyleOpts (curve = 0.2), ).set_series_OPts (label_opts= opts.labelopts (is_show=False)).set_global_opts(title_OPts = opts.titLeopts (title=" dynamic track ")) .render("geo_lines_background.html") )Copy the code

The running effect is as follows:

3. Provincial map — data visualization

Heat map

The code is as follows:

from pyecharts import options as opts from pyecharts.charts import Geo from pyecharts.faker import Faker from pyecharts.globals import GeoType, CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' c = ( Geo() .add_schema(mapType =" GDD ", label_opts= opts.labelopts (is_show=True)).add(" GDD ", [list(z) for z in zip(Faker.guangdong_city, Faker.values())], type_=GeoType.HEATMAP, ) .set_series_opts(label_opts=opts.LabelOpts(is_show=True)) .set_global_opts( visualmap_opts=opts.VisualMapOpts(), Title_opts = opts.titleopts (title=" geo_guangdong ")).render("geo_guangdong "))Copy the code

The running effect is as follows:

Add address, latitude and longitude data in batches on the map and visualize geographic data

The code is as follows:

Charts import Geo # Import options from Pyecharts import options as OPts # from pyecharts.globals import GeoType, CurrentConfig, ThemeType CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' df = pd.read_excel("hotel.xlsx") # Location geo_SIGHT_COord = {df.iloc[I][' hotel address ']: [df iloc [I] [' longitude '], df, iloc [I] [' latitude]] for I in range (len (df)} data = [(df [' hotel address] [j], F "{int(df[' sight_low '][j])} yuan (low)") for j in range(len(df))] # print(data) # print(geo_sight_coord) g = Geo(init_opts=opts.InitOpts(theme=ThemeType.PURPLE_PASSION, width="1000px", Height ="600px")) for k, v in list(geo_sight_coord.items()): · Dd_coordinate (k, V [0], V [1]) · Dd_coordinate ("", data_pair=data, type_=GeoType.EFFECT_SCATTER, symbol_size=6) g.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) G. set_global_opts(title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts))Copy the code

The running effect is as follows:

3. Bar chart

The code is as follows:

from pyecharts.charts import Bar from pyecharts.faker import Faker from pyecharts.globals import ThemeType, CurrentConfig from pyecharts import options as opts CurrentConfig.ONLINE_HOST = C = (Bar(init_opts= opts.initopts (# InitOpts =ThemeType.MACARONS))  animation_opts=opts.AnimationOpts( animation_delay=1000, Add_yaxis (xaxis_data= faker.choose ()) # xaxis. Add_yaxis (series_name=" c ", Yaxis_data = faker.values ()) # yax.add_yaxis (series_name=" B", Yaxis_data = faker.values ()) # y ax.set_global_opts (title_opts= opts.titleopts (title=' title ', subtitle=' subtitle ', Title_textstyle_opts = opts.textStyLeopts (font_family='SimHei', font_size=25, font_weight='bold', Color = 'red'), pos_left = "90%", pos_top = "10",), xaxis_opts = opts. AxisOpts (name = 'x name, Axislabel_opts = opts.labelopts (rotate=45)), # rotate and Label rotate ) .render("bar_001.html") )Copy the code

The running effect is as follows:

The code is as follows:

import pandas as pd import collections from pyecharts import options as opts from pyecharts.charts import Bar from pyecharts.globals import ThemeType, CurrentConfig import random CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' df = Read_excel ("hotel.xlsx") area = list(df[' hotel.xlsx ']) area_list = [] for I in area: I = I [:_index + 1] area_list.appEnd (I) area_count = collections.counter (area_list) Area_dic = dict(area_count) # Number of hotels for two lists Area_dic = dict(area_count) # Number of hotels for two lists Area_dic = dict(area_count) # Number of hotels for two lists Area = [x for x in list(area_dic.keys())][0:10] nums = [y for y in List (area_dic. Values ())][:10] # color = bar (init_opts= opts.initopts (theme= themetype.macarons)) colors = ['red', '#0000CD', '#000000', '#008000', '#FF1493', '#FFD700', '#FF4500', '#00FA9A', '#191970', Baritem y = [] for I in range(10): y.append( opts.BarItem( value=nums[i], Itemstyle_opts = opts.itemStyLeopts (color=colors[I]) # bar.add_xaxis(xaxis_data=area) bar.add_yaxis Yaxis_data =y) bar.set_global_opts(xaxis_opts= opts.axisopts (name=' admin ', axislabel_opts= opts.labelopts (rotate=45)), Yaxis_opts = opts.axisopts (name=' number of hotels ', min_=0, max_=330, # yaxis scale minimum maximum value), title_opts= opts.titleopts (title=" number of hotels - hotels ", title_textstyle_opts=opts.TextStyleOpts( font_family="KaiTi", font_size=25, Bar.set_series_opts (label_opts= opts.labelopts (is_show=False), Markpoint_opts = opts.markPointopts (data=[opts.markPointitem (type_=" Max ", name=" Max "), opts.markPointitem (type_="min", Opts.MarkPointItem(type_="average", name=" average")), markline_opts=opts.MarkLineOpts( data=[ opts.MarkLineItem(type_="average", Name =" average ")])) bar.render(" Top10 ")Copy the code

The running effect is as follows:

The code is as follows:

from pyecharts import options as opts from pyecharts.charts import Bar from pyecharts.faker import Faker from pyecharts.globals import ThemeType, CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' c = ( Bar(init_opts= opts.initopts (theme= themetype.dark)).add_xaxis(xaxis_data= faker.days_attrs).add_yaxis(" business A", Yaxis_data = faker.days_values).set_global_opts(title_opts= opts.titleopts (title=" bar-datazoom (slider+inside) "), datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], ) .render("bar_datazoom_both.html") )Copy the code

The running effect is as follows:

Fourth, the pie chart

The code is as follows:

from pyecharts import options as opts from pyecharts.charts import Pie from pyecharts.faker import Faker from pyecharts.globals import CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' c = ( Pie().add("", [list(z) for z in zip(faker.choose (), faker.values ())], When you set it to a percentage, the first term is relative to the container width, The second is relative to the height of container center = [" 35% ", "50%"],). Set_colors ([" blue ", "green", "yellow", "red", "pink", "orange". Title_opts = opts.titleopts (title_opts= opts.titleopts (title_opts= "Pie- set color - adjust legend position "), legend_opts=opts.LegendOpts(type_="scroll", pos_left="70%", orient="vertical"), Set_series_opts (label_opts= opts.labelopts (formatter="{b}: {c}")).render("pie_set_color.html")Copy the code

The running effect is as follows:

The code is as follows:

import pyecharts.options as opts from pyecharts.charts import Pie from pyecharts.globals import CurrentConfig Currentconfig. ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' x_data = [" Deep Learning ", "Data Analysis ", "Web development "," crawler ", Y_data = [list(z) for z in zip(x_data, x_data) y_data)] data_pair.sort(key=lambda x: X [1]) c = Pie(init_opts= opts.initopts (width="1200px", height="800px", Bg_color ="# 2c343C ")). Add (series_name=" 中 文 名 ", # series data_pair=data_pair, # series data_pair, Format: [(key1, value1), (key2, value2)] roseType ="radius", # radius: Radius ="55%", # pie radius center=["50%", "50%"], # pie center (center) coordinates, the first item of the array is the x-coordinate, Label_opts = opts.labelopts (is_show=False, position="center"), Set_global_opts (title_OPts = opts.titleopts (title="Customized Pie", pos_left="center", pos_top="20", title_textstyle_opts=opts.TextStyleOpts(color="#fff"), ), legend_opts=opts.LegendOpts(is_show=False), ) .set_series_opts( tooltip_opts=opts.TooltipOpts( trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)" # 'item': Data item graph trigger, mainly in scatter plot, Label_opts = opts.labelopts (color="rgba(255, 255, 255, 0.3)"),).render("customized_pie.html"))Copy the code

The running effect is as follows:

Five, the ring

The code is as follows:

from pyecharts import options as opts from pyecharts.charts import Pie from pyecharts.faker import Faker from pyecharts.globals import CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' c = ( Pie().add("", [list(z) for z in zip(faker.choose (), faker.values ())], Relative to the container a half the radius of the smaller of high to width = "40%", "60%"],). Set_colors ([" blue ", "green", "# 800000", "red", "# 000000", "orange". "purple"]) .set_global_opts( title_opts=opts.TitleOpts(title="Pie-Radius"), legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"), ) .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}")) .render("pie_radius.html") )Copy the code

The running effect is as follows:

The code is as follows:

from pyecharts import options as opts from pyecharts.charts import Pie from pyecharts.faker import Faker from pyecharts.globals import CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' c = ( Pie() .add( "", [list(z) for z in zip(Faker.choose(), Faker.values())], radius=["40%", "60%"], label_opts=opts.LabelOpts( position="outside", formatter="{a|{a}}{abg|}\n{hr|}\n {b|{b}: }{c} {per|{d}%} ", background_color="#eee", border_color="#aaa", border_width=1, border_radius=4, rich={ "a": {"color": "#999", "lineHeight": 22, "align": "center"}, "abg": { "backgroundColor": "#e3e3e3", "width": "100%", "align": "right", "height": 22, "borderRadius": [4, 4, 0, 0], }, "hr": { "borderColor": "#aaa", "width": "100%", "borderWidth": 0.5, "height" : 0}, "b" : {" fontSize ": 16," lineHeight ": 33}," per ": {" color" : "# eee", "backgroundColor" : "#334455", "padding": [2, 4], "borderRadius": Set_global_opts (title_opts= opts.titleopts (title=" pie-rich text sample ")).render("pie_rich_label.html"))Copy the code

The running effect is as follows:

6. Roses

The code is as follows:

from pyecharts import options as opts from pyecharts.charts import Pie from pyecharts.faker import Faker from pyecharts.globals import CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' labels = [' coke ', Sprite, orange juice, milk tea, cold beer, 'lemonade'] values = [6, 12, 28, 52, 72, 96] v = Faker. Choose () = c (Pie (), add (" ", [list(z) for z in zip(v, Faker.values())], radius=["40%", "75%"], center=["22%", "50%"], rosetype="radius", label_opts=opts.LabelOpts(is_show=False), ) .add( "", [list(z) for z in zip(labels, values)], radius=["40%", "75%"], Center =["70%", "50%"], roseType ="area",).set_global_opts(title_opts= opts.titleopts (title=" pie-rose example "), legend_opts=opts.LegendOpts(is_show=False) ) .render("pie_rosetype.html") )Copy the code

from pyecharts import options as opts from pyecharts.charts import Pie from pyecharts.globals import CurrentConfig import pandas as pd CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' provinces = [' Beijing ', 'Shanghai', 'in heilongjiang, jilin, liaoning, Inner Mongolia, xinjiang, Tibet, qinghai, sichuan, yunnan, shaanxi, chongqing, 'guizhou', ' 'in guangxi, hainan,' the ', 'hunan', 'jiangxi, fujian, anhui, zhejiang, jiangsu, ningxia, shanxi,' hebei ', 'tianjin'] num = Color_series =,1,1,17,9,22,23,42,35,7,20,21,16,24,16,21,37,12,13,14,13,7,22,8,16,13,13 [1] ['#FAE927','#E9E416','#C9DA36','#9ECB3C','#6DBC49', '#37B44E','#3DBA78','#14ADCF','#209AC9','#1E91CA', '#2C6BA0','#2B55A1','#2D3D8E','#44388E','#6A368B' '#7D3990','#A63F98','#C31C88','#D52178','#D5225B', '#D02C2A','#D44C2D','#F57A34','#FA8F2F','#D99D21', '#CF7B25','#CF7B25','#CF7B25'] # create DataFrame df = pd. Df. sort_values(by='num', ascending=False, Value. Tolist () d = df['num'].values. Tolist ( Pie(init_opts= opts.initopts (width='1250px', height='750px')) # pie1.set_colors(color_series) pie1.add("", [list(z) for z in zip(v, d)], radius=["30%", "100%"], center=["50%", "50%"], Pie1.set_global_opts (title_opts= opts.titleopts (title=' n confirmed cases for several days ',subtitle=' zero new cases ', title_textstyle_opts=opts.TextStyleOpts(font_size=25,color= '#0085c3'), subtitle_textstyle_opts= opts.TextStyleOpts(font_size=50,color= '#003399'), pos_right= 'center',pos_left= 'center',pos_top='42%',pos_bottom='center' ), legend_opts=opts.LegendOpts(is_show=False), Pie1.set_series_opts (label_opts= opts.labelopts (is_show=True, Position ="inside", font_size=12, formatter="{b}:{c} day ", font_style="italic", font_weight="bold", font_family="SimHei"), Pie1.render (' Nightingale rose example.html ') # pie1.render(' Nightingale rose example.html ')Copy the code

The running effect is as follows:

Word cloud map

Word cloud is to filter out a large amount of text information by forming keyword cloud or keyword rendering, so as to visually highlight the keywords with high frequency in network text.

import jieba import collections import re from pyecharts.charts import WordCloud from pyecharts.globals import SymbolType from pyecharts import options as opts from pyecharts.globals import ThemeType, CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' with open('barrages.txt') as f: New_data = re.findall('[u4e00-\u9fa5]+', data, Join (new_data) # text segmentation -- exact mode seg_list_exact = jieba.cut(new_data, cut_all=False) result_list = [] with open('stop_words.txt', encoding='utf-8') as f: con = f.readlines() stop_words = set() for i in con: I = i.replace("\n", "") # remove \n stop_words. Add (I) for word in seg_list_exact: If word not in stop_words and len(word) > 1: Word_counts = collections.Counter(result_list) # fetch the top 100 most common words Print (word_counts_top100) # chain call c = (WordCloud() Init_opts = opts.initopts (width='1350px', height='750px', theme= themetype.macarons). Add (series_name=" word-frequency ", [(word1, count1), (word2, count2)] word_size_range=[15, 108], Textstyle_opts = opts.textStyLeopts (font_family='KaiTi',), shape=SymbolType.DIAMOND, 'circle', 'cardioid', 'diamond', 'triangle-forward', 'triangle', 'pentagon', 'star' pos_left='100', Set_global_opts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts), title_textstyle_opts=opts.TextStyleOpts( font_family='SimHei', font_size=25, color='black' ), pos_left='500', Pos_top ='10',), tooltip_opts= opts.tooltipopts (# prompt box config is_show=True, background_color='red', border_color='yellow', ), toolbox_opts= opts.toolboxopts (# toolbox config is_show=True, Orient ='vertical',)).render(' bullet-email.html '))Copy the code

The running effect is as follows:

Instrument panel

from pyecharts.charts import Gauge from pyecharts.globals import CurrentConfig from pyecharts import options as opts Currentconfig.online_host =' D:/python/pyecharts-assets-master/assets/' c = (Gauge().add(series_name=' business indicator ', # series_name=' business indicator ', For tooltip display, legend filter. Data_pair =[[' completion rate ', 88.8]], # series data item in the format [(key1, Value1), (key2, value2)] RADIUS ='70%', # Dashboard radius, which can be half the percentage of the smaller item in the container height and width, It could be an absolute number. Axisline_opts = opts.axislineOpts (linestyLE_OPts = opts.linestyLeopts (# coordinate axis configuration item color=[(0.3, "# 67e0E3 ")), (0.7, "#37a2da"), (1, "#fd666d")], width=30,)), title_label_opts= opts.labelopts Color ='blue', font_family='KaiTi').set_global_opts(title_opts= opts.titleopts) title_textstyle_opts=opts.TextStyleOpts( font_size=25, font_family='SimHei', color='black', font_weight='bold', ), Pos_left ="410", pos_top="8",), legend_opts= opts.legendopts (# is_show=False), Tooltip_opts = opts.tooltipopts (is_show=True, formatter="{a} <br/>{b} : {c}%",)).render('gauge.Copy the code

The running effect is as follows:

Water balloon diagram

from pyecharts import options as opts from pyecharts.charts import Grid, Liquid from pyecharts.commons.utils import JsCode from pyecharts.globals import CurrentConfig, ThemeType CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' lq_1 = ( Liquid() .add( Series_name =' power ', # series name, used for tooltip display, legend filter. Data =[0.25], # series data in the format of [value1, value2,....] Center = [' 60% ', '50%'], # water polo appearance, have 'circle', 'the rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow is optional. Shape ='circle', color=['yellow'], # wave color Optional[Sequence[STR]] = None, Is_animation =True, # is_outline_show=False, Set_global_opts (title_opts= opts.titLeopts (title=' multiple Liquid displays ')) lq_2 = (Liquid().add(series_name=' data precision ', Data =[0.8866], center=['25%', '50%'], label_opts= opts.labelopts (font_size=50, formatter=JsCode( """function (param) { return (Math.floor(param.value * 10000) / 100) + '%'; }""" ), position='inside' ) ) ) grid = Grid(init_opts=opts.InitOpts(theme=ThemeType.DARK)).add(lq_1, grid_opts=opts.GridOpts()).add(lq_2, grid_opts=opts.GridOpts()) grid.render("multiple_liquid.html")Copy the code

The running effect is as follows:

Data acquisition

Source: www.tianqihoubao.com/aqi/chengdu…

Climb the annual air quality data of Chengdu in 2019

import pandas as pd dates = pd.date_range('20190101', '20191201', Freq ='MS').strftime('%Y%m') # construct url for I in range(len(dates)): df = pd.read_html(f'http://www.tianqihoubao.com/aqi/chengdu-{dates[i]}.html', encoding='gbk', header=0)[0] if i == 0: Df.to_csv ('2019 Chengdu Air quality data. CSV ', mode='a+', index=False) # append I += 1 else: Df.to_csv ('2019 Air quality data in Chengdu. CSV ', mode='a+', index=False, header=False)Copy the code

View the crawled data

Ten, line chart

A line chart is the data arranged in columns or rows of a worksheet that can be plotted onto a line chart. Line charts can show continuous data over time (based on common scale Settings), making them ideal for showing trends in data over equal time intervals.

Chart the trend of Chengdu AQI index in 2019

import pandas as pd import pyecharts.options as opts from pyecharts.charts import Line from pyecharts.globals import CurrentConfig CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' df = CSV ') date = [x for x in range(len(df[' date '])] value = [int(I) for I in df['AQI index ']]] # Line = line () line.add_xaxis(xaxis_data=date) line.add_yaxis("AQI index ", # series data item value, # opacity=0; # opacity=0; # opacity=0; # opacity=0; # opacity=0 Label_opts = opts.labelopts (is_show=False), # markPoint_opts = opts.markPointopts (# markPoint_data =[opts.markPointitem (type_=" Max ", name=" Max "), Opts.markpointitem (type_="min", name=" min"), opts.markPointitem (type_="average", name=" average")), Markline_opts = opts.marklineOpts (# markline config item data=[opts.marklineItem (type_="average", Name =" average ")]) line.set_global_opts(title_opts= opts.titLeopts (title_opts= opts.titLeopts)) Line.render ('2019 Chengdu AQI index trend chart (daily statistics).html')Copy the code

The running effect is as follows:

import pandas as pd import pyecharts.options as opts from pyecharts.charts import Line from pyecharts.globals import CurrentConfig, ThemeType import math CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' df = Pd. Read_csv (' air quality data in chengdu in 2019. The CSV) [[' date ', 'AQI index]] data = df [' date'] STR. Split (' - ' Expand =True)[1] df[' 200 '] = data # count = df.groupby(' 200 ').agg({' 200 ': 'mean'}) date = [f'{x} month 'for x in range(1, 13)] value = [math.ceil(I) for I in counts['AQI ']] line = line (init_opts= opts.initopts (theme= themetype.dark)) Line.set_colors (['red']) line.add_xaxis(xaxis_data=date) line.add_yaxis("AQI index mean ", Label_opts = opts.labelopts (is_show=False), Markpoint_opts = opts.markPointopts (# markpoint configuration item data=[opts.markPointitem (type_=" Max ", name=" Max "), Opts.markpointitem (type_="min", name=" min"), opts.markPointitem (type_="average", name=" average")), Markline_opts = opts.marklineOpts (# markline config item data=[opts.marklineItem (type_="average", Title_opts = opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts (title_opts= opts.titleopts)), pos_left='32%', pos_top='3%', title_textstyle_opts=opts.TextStyleOpts( font_family='SimHei', font_size=20, color='#F0FFF0' ) ), Xaxis_opts = opts. AxisOpts (name = 'in'), # yaxis_opts= opts.axisopts (name='AQI index mean ') # yaxis_opts= opts.axisopts (name='AQI index mean ')Copy the code

The running effect is as follows:

11. Box diagram

A box-plot, also called a box-and-whisker plot, box-and-whisker plot, or box-and-whisker plot, is a statistical plot used to show information about the dispersion of a group of data. Named for its shape like a box. It is also commonly used in a variety of fields and is commonly used in quality management. It is mainly used to reflect the distribution characteristics of original data, and can also compare the distribution characteristics of multiple groups of data. A boxplot is drawn by finding the upper edge, lower edge, median and two quartiles of a set of data. Then, connect the two quartiles to draw the box; The upper edge and the lower edge are connected with the box body, and the median is in the middle of the box body.

import pandas as pd from pyecharts import options as opts from pyecharts.charts import Boxplot from pyecharts.globals import CurrentConfig, ThemeType CurrentConfig.ONLINE_HOST = 'D:/python/pyecharts-assets-master/assets/' df = Pd.read_csv (' air quality data of Chengdu in 2019. CSV ')[[' date ', 'AQI index ']] df.sort_values(by='AQI index ', Split ('-', expand=True)[1] df[' groove '] = data item1, item2, item3, Item4 = [], [], [], [] # is divided into four quarters for I and j in zip (df [' in '], df [' AQI index]) : if I in [' 01 ', '02', '3') : item1.append(j) elif i in ['04', '05', '06']: item2.append(j) elif i in ['07', '08', '09']: item3.append(j) elif i in ['10', '11', '12']: For I in range(1, 5)] y_data = [item1, item2, item3, y_data = [item1, item2, item3, item4] boxplot = Boxplot(init_opts=opts.InitOpts(theme=ThemeType.MACARONS)) boxplot.set_colors(['red']) boxplot.add_xaxis(xaxis_data=x_data) boxplot.add_yaxis(series_name='', Prepare_data (y_data)) boxplot.set_global_opts(title_OPts = opts.titleopts (title='2019 Chengdu SEASON AQI index box chart ', pos_left='300', pos_top='5', title_textstyle_opts=opts.TextStyleOpts( font_family='KaiTi', font_size=20, Color ='black'), xaxis_opts= opts.axisopts (name=' quarter '), Yaxis_opts = opts.axisopts (name='AQI index ')) boxplot.render('2019 Chengdu quarter AQI index box graph.html ')Copy the code

The running effect is as follows:

Public number: Jie ge’s IT journey, reply below“Key words”, access to quality resources

  • Reply the keyword “CDN”, you can get 89 pages of CDN drainage Guide manual
  • Reply the keyword “ECS” to obtain the 96-page DIAGNOSTIC manual of THE ECS O&M Linux system
  • Reply to “Linux” for a 185 page quick Tutorial on Linux tools
  • Reply to the keyword “Advanced Python” to obtain 106 pages of Advanced Python documentation PDF
  • Reply to “Python automation” to obtain a 97-page automation document PDF
  • Reply to the keyword “Excel PivotTable” to obtain 136 pages of Excel PivotTable PDF
  • Reply to the keyword “Python Strongest Basic Learning Document” to obtain the 68-page Python Strongest Basic Learning Document PDF
  • Reply to the keyword “wX”, you can join the IT travel reader communication group of Jie Ge

Original is not easy, code word is not easy, if you think this article is a bit useful to you, please leave a message for this article, point to see, or forward it, let more people see. Because this will be my continuous output of more high-quality articles the strongest power! Thank you!