Pyechart: 30 minute guide to data visualization pyecharts

30 minutes to learn the data visualization pyecharts

Alice: You should talk to me about what is pyecharts it.

 

Xiao Ming: Echarts of Baidu is a open source data visualization javascript library with a good interactive, sophisticated graphic design, has been recognized by many developers. The Python is an expressive language, it is suitable for data processing. When the data analysis encounter data visualization, pyecharts born. Simply put, pyecharts Baidu is a powerful javascript open source data visualization library Echarts the python interface.

 

Red: I understand that this pyecharts how to install it?

 

Xiao Ming: very simple, with a pip can be installed. The following is an exemplary installation of the library in the jupyter notebook.

 

# 安装pyecharts
!pip install pyecharts==0.5.11

# pyecharts_snapshot 提供图片导出功能
!pip install pyecharts_snapshot

  

First, the basic chart

 

Alice: Well, I have installed a success. Can you give me some examples of commonly used chart.

 

Bob: OK, the most commonly used in the data analysis of 3 chart is a column chart, a line chart and scatter plots. Here we look at the example pyecharts draw these three common chart it.

 

1, Column

  

Suitable for the performance bar graph comparing the relationship between several sets of data, the number of bar graph performance data is generally not too much, more words will be like a bunch of weeds.

 

from  pyecharts import Bar

x = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋"]
y1 = [5, 20, 36, 10, 75]
y2 = [10, 25, 8, 60, 20]

bar = Bar(title = "产品月销量",width = 600,height = 420)
bar.add(name = "商家A", x_axis = x, y_axis = y1)
bar.add(name = "商家B", x_axis = x, y_axis = y2,is_xaxis_boundarygap =True)

# 导出绘图html文件,可直接用浏览器打开
bar.render('柱形图示范.html')
bar

   

2, line

 

Suitable FIG polyline function describing the relationship between two variables, for example, a variable used to describe the trend over time.

 

from  pyecharts import Line

x = ['2018-{:0>2d}'.format(s) for s in range(1,13)]
y1 = [5,10,26,30,35,30,20,26,40,46,40,50]
y2 = [8,20,24,36,40,36,40,45,50,53,48,58]

line = Line(title = "月销售总额",width = 600,height = 420)

line.add(name = "商家A", x_axis = x, y_axis = y1,
         line_width = 3,line_color = 'red')
line.add(name = "商家B", x_axis = x, y_axis = y2,
         yaxis_min = 0,yaxis_max = 100,is_xaxis_boundarygap = False,
         is_datazoom_show =True,line_width = 2,line_color = 'cyan')

line.render('折线图示范.html')
line

  

3, scatter

Scatter distribution of large number of samples suitable for the performance of multiple properties. Each point represents one sample scattergram, showing an attribute of each coordinate dimension.

 

from pyecharts import Scatter
import pandas as pd 

dfboy = pd.DataFrame()
dfboy['weight'] = [56,67,65,70,57,60,80,85,76,64]
dfboy['height'] = [162,170,168,172,168,172,180,176,178,170]

dfgirl = pd.DataFrame()
dfgirl['weight'] = [50,62,60,70,57,45,62,65,70,56]
dfgirl['height'] = [155,162,165,170,166,158,160,170,172,165]

scatter = Scatter(title = "体格数据",width = 600,height = 420)
scatter.add(name = "boy", x_axis = dfboy['weight'], y_axis = dfboy['height'])
scatter.add(name = "girl", x_axis = dfgirl['weight'], y_axis = dfgirl['height'],
           yaxis_min = 130,yaxis_max = 200,xaxis_min = 30,xaxis_max = 100)

scatter.render("散点图示范.html")

scatter

 

When more than two dimensions of the sample properties, scatter more properties may be expressed using dimension point of the color or size. The following demonstrates the use of dot size represents three dimensions.

 

from pyecharts import Scatter
import pandas as pd 

def custom_formatter(params):
    return (params.value[3] + ':' +
             str(params.value[0]) +','
             +str(params.value[1]) + ','
             +str(params.value[2]))

df = pd.DataFrame()
df['country'] = ["中国",'美国','德国','法国','英国','日本','俄罗斯','印度','澳大利亚','加拿大']
df['life-expectancy'] = [76.9,79.1,81.1,81.9,81.4,83.5,73.13,66.8,81.8,81.7]
df['capita-gdp'] = [13334,53354,44053,37599,38225,36162,23038,5903,44056,43294]
df['population'] = [1376048943,321773631,80688545,64395345,64715810,126573481,143456918,
                    1311050527,23968973,35939927]

scatter = Scatter(title = "各国发展水平",width = 600,height = 420)
scatter.add(name = '',
            x_axis = df['capita-gdp'],  # params.values[0]
            y_axis = df['life-expectancy'], # params.values[1]
            extra_data = df['population'].values.tolist(), # params.values[2]
            extra_name = df['country'].values.tolist(), # params.values[3]
            tooltip_formatter=custom_formatter,  #自定义提示框格式内容
            is_visualmap=True, 
            visual_orient="horizontal",
            visual_type = 'size',  #可以是size或者color
            visual_dimension=2,
            visual_range=[20000000, 1500000000],
           )
scatter

  

Little Red: You say most of these examples above is quite simple, this may scatter plot to show the level of development of each country's relatively complex example, if there is not a 3-dimensional data will be passed by extra_data it? Visual_dimension then used to specify the size of the color represented by point or several points of the first dimensional data. Here, then, with the size of the dot indicates the population is, how much each country's population. right?

 

Xiao Ming: is also not wrong, you can follow the example of this point try to use color to represent the third dimension of data should not be difficult to understand.

 

Red: Bang Bang. In addition to these three most commonly used chart. There are some other handy chart of strong performance can recommend?

 

Xiao Ming: you really feel bored. I give you demonstrate what box plot, word cloud and geographic coordinate system drawing.

 

4, FIG box

 

FIG box statistical distribution suitable for the performance of a set of data, it can display a maximum value of a set of data, minimum, median, and upper and lower quartiles.

Advanced versions of the violin is a box diagram of FIG, we can show density estimation curve data can be used to draw seaborn.

 

from pyecharts import Boxplot

x =['1班','2班','3班','4班']
y1=[78, 98, 56, 78, 90.0, 45, 78, 20, 87, 86, 74, 89, 94]
y2=[89, 82, 45, 67, 68, 78.0, 79, 98, 71, 56, 78, 81, 80]
y3=[90, 80, 60, 89, 76, 73.0, 72, 92, 89, 87, 65, 66, 76]
y4=[82, 72, 55, 100, 90.0, 78, 69, 67, 87, 66, 78, 71, 82]

box = Boxplot(title = '考试成绩箱型图',width = 600,height = 420)

# 预处理数据计算最大值,最小值,中位数以及上下四分位数
y_prepared = box.prepare_data([y1,y2,y3,y4]) 
box.add(name = '',x_axis = x,y_axis = y_prepared)

 

Annex: FIG violin drawn by seaborn

 

import seaborn as sns
%matplotlib inline
%config InlineBackend.figure_format = 'svg'

#设置风格
sns.set(style="white", context="notebook")
#处理中文问题
sns.set_style({'font.sans-serif':['simhei', 'Arial']}) 

dfdata = pd.DataFrame()
dfdata['score'] = y1 + y2 + y3 + y4
dfdata['class'] = ['1班']*len(y1)+['2班']*len(y2)+['3班']*len(y3)+['4班']*len(y4)

ax = sns.violinplot(x= 'class', y = 'score',data = dfdata,
            palette = 'hls', # 设置调色板
            inner = 'box'# 设置内部显示类型 → “box”, “quartile”, “point”, “stick”, None
           )

  

5, word cloud

 

Word cloud for the performance of the frequency of occurrence or the extent of the importance of different keywords.

 

from pyecharts import WordCloud

words = ['python','jupyter','numpy','pandas','matplotlib','sklearn',
        'xgboost','lightGBM','simpy','keras','tensorflow',
         'hive','hadoop','spark']
counts = [100,90,65,95,50,60,70,70,20,70,80,80,60,60]

cloud = WordCloud(title = '数据算法常用工具',width = 600,height = 420)
cloud.add(name = 'utils',attr = words,value = counts,
          shape = "circle",word_size_range = (10,70))
cloud

 

6, the geographic coordinate system of FIG.

 

Map for geographic coordinate system performance and national, provincial, city and distribution of data, latitude and longitude associated with it.

pyecharts Geo expression in the city and associated data, Map and expression data associated countries and provinces.

 

# 安装地图附属包
!pip install echarts-countries-pypkg
!pip install echarts-china-provinces-pypkg
!pip install echarts-china-cities-pypkg

 

# 全国城市地图示例
from pyecharts import Geo

data = [
    ("海门", 9),("鄂尔多斯", 12),("招远", 12),("舟山", 12),("齐齐哈尔", 14),("盐城", 15),
    ("惠州", 37),("江阴", 37),("蓬莱", 37),("韶关", 38),("嘉峪关", 38),("广州", 38),
    ("张家港", 52),("三门峡", 53),("锦州", 54),("南昌", 54),("柳州", 54),("三亚", 54),
    ("呼和浩特", 58),("成都", 58),("大同", 58),("镇江", 59),("桂林", 59),("张家界", 59),
    ("北京", 79),("徐州", 79),("衡水", 80),("包头", 80),("绵阳", 80),("乌鲁木齐", 84),
    ("菏泽", 194),("合肥", 229),("武汉", 273),("大庆", 279)]

geo = Geo(
    "全国部分城市空气质量",
    title_color="#fff",
    title_pos="center",
    width=800,
    height=600,
    background_color="#404a59",
)
attr, value = geo.cast(data)
geo.add(
    "",
    attr,
    value,
    visual_range=[0, 200],
    visual_text_color="#fff",
    symbol_size=15,
    is_visualmap=True,
)
geo

  

#  全国省份地图
from pyecharts import Map
value = [155, 10, 66, 78, 44, 38, 88, 50, 20]
attr = ["福建","山东","北京","上海","江西","新疆","内蒙古","云南","重庆"]
m = Map("全国省份地图", width=600, height=400)
m.add("", attr, value, maptype='china',
        is_visualmap=True, 
        is_piecewise=True,
        visual_text_color="#000",
        visual_range_text=["", ""],
        pieces=[
            {"max": 160, "min": 81, "label": "高"},
            {"max": 80, "min": 51, "label": "中"},
            {"max": 50, "min": 0, "label": "低"},
        ])
m

  

# 世界地图示例
from pyecharts import Map
countries= ["China", "Canada", "India", "Russia", "United States","Japan"]
capita_gdp = [13334, 43294, 5903, 23038, 53354,36162]
population = [1376048943, 35939927, 1311050527, 143456918, 321773631,126573481]
life_expectancy = [76.9,81.7,66.8,73.13,79.1,73.13]

m = Map("世界经济发展水平", width=800, height=500)
m.add(
    "人均GDP",
    attr = countries,
    value = capita_gdp,
    maptype="world",
    is_visualmap=True,
    visual_range = [5000,60000],
    visual_text_color="#000",
    is_map_symbol_show=False,
    visual_orient="horizontal"
)
m

  

Second, chart configuration

 

Little Red: The basic chart you described above Duman practical, make it seem too hard. But if I want to chart size, line color, axis scale and some details to adjust, rather than use the default settings, how to do it?

 

Xiao Ming: You say this is called the chart configuration. There are three methods to configure the chart in pyecharts years.

 

The first theme is to modify the chart styles: the use or configure use_theme specify chart style theme, have an impact on the overall style of the color chart.

 

The second graph is initialized common attributes: the chart specified height, title attributes when creating a chart, an impact on the general properties of the image size and the like of the title.

 

The third element is the configuration-specific attributes: the chart may be used to add a particular configuration element properties xyAxis, datazoom, lineStyle like.

 

1, modify the chart theme style

 

Use_theme can be used to modify a single chart theme, you can modify the global chart style with configure.

 

# 默认主题效果
import random
from pyecharts import Bar

X_AXIS = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
bar = Bar("默认主题效果", "这里是副标题")
bar.add("商家A", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家B", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家C", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家D", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar

 

# 使用dark主题
import random
from pyecharts import Bar


X_AXIS = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
bar = Bar("dark主题展示", "这里是副标题")
bar.use_theme("dark")
bar.add("商家A", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家B", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家C", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家D", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar

  

# 安装主题插件获取更多主题
!pip install echarts-themes-pypkg

 

Theme plug-in supports the following topics

  • vintage

  • macarons US

  • shine beauty +++

  • roma beauty

  • westeros

  • wonderland

  • chalk

  • halloween  美+

  • Essos

  • walden

  • purple-passion

  • romantic

 

import random
from pyecharts import Bar

X_AXIS = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
bar = Bar("shine主题展示", "这里是副标题")
bar.use_theme("shine")
bar.add("商家A", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家B", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家C", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar.add("商家D", X_AXIS, [random.randint(10, 100) for _ in range(6)])
bar

  

If you want to set a theme style applied to all charts can be set by configure before drawing begins.

 

from pyecharts import configure
# 将这行代码置于首部
configure(global_theme='shine')


from pyecharts import Pie
attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
value = [11, 12, 13, 10, 10, 10]
pie = Pie("销售额占比",width = 800,height = 520)
pie.add("", attr, value, is_label_show=True)

 

2, common attributes modify the chart

 

Chart common attribute refers chart title, subtitle, height, width, title_pos , title_color, title_text_size, background_color other attributes which charts are applicable to all types.

See all the common property of the way pyecharts detailed official document: https: //github.com/lyhue1991/pyecharts/blob/master/docs/zh-cn/charts_configure.md

 

from pyecharts import Pie
attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
value = [11, 12, 13, 10, 10, 10]

# 初始化图表通用属性
pie = Pie(title = "销售额占比",
          title_pos = 'center', # 标题居中
          title_top = 'bottom', # 标题在底部
          title_color = '#0000ff', # 标题颜色设置为蓝色,256位rgb格式
          background_color = "#aee", # 设置背景颜色,16位rgb格式
          width = 600,height = 420)

pie.add("", attr, value, is_label_show=True)

  

3, a specific configuration element properties

 

Element attributes include specific xyAxis, dataZoom, lineStyle, markLine-markPoint, visualMap attributes and other elements, these elements apply only in certain types of charts. For example xyAxis applies only in Line, Bar, Scatter, EffectScatter, Kline these types of charts.

 

All element attributes specific arrangement See detailed official document: https: //github.com/lyhue1991/pyecharts/blob/master/docs/zh-cn/charts_configure.md

 

# 设置xyAxis示范

from  pyecharts import Line

x = ['2018-{:0>2d}'.format(s) for s in range(1,13)]
y1 = [5,10,26,30,35,30,20,26,40,46,40,50]
y2 = [8,20,24,36,40,36,40,45,50,53,48,58]

line = Line(title = "月销售总额",width = 600,height = 420)

line.add(name = "商家A", x_axis = x, y_axis = y1)
line.add(name = "商家B", x_axis = x, y_axis = y2,
         #
         #=====设置xyAxis=====
         yaxis_min = 0,yaxis_max = 100,  # 设置y坐标轴刻度范围
         xaxis_name = '月份', yaxis_name = '销售额', #x轴名称,y轴名称
         xaxis_name_gap =  40, # x轴名称与轴距离
         xaxis_rotate = 30,  # x轴刻度旋转角度
         is_splitline_show = True, # 显示y轴网格线
         is_xaxislabel_align = True # x轴刻度和标签是否对齐
        )
line

  

# 设置dataZoom示范
from  pyecharts import Line

x = ['2018-{:0>2d}'.format(s) for s in range(1,13)]
y1 = [5,10,26,30,35,30,20,26,40,46,40,50]
y2 = [8,20,24,36,40,36,40,45,50,53,48,58]

line = Line(title = "月销售总额",width = 600,height = 420)

line.add(name = "商家A", x_axis = x, y_axis = y1)
line.add(name = "商家B", x_axis = x, y_axis = y2,
         #
         #=====设置xyAxis=====
         is_xaxis_boundarygap = False,  # x坐标刻度对准数据,而不是作为分类边界
         #
         #=====设置dataZoom=====
         is_datazoom_show = True, #显示 dataZoom控制条
         datazoom_type = 'both' # 可以是slider,inside或both
         #
         #
        )
line

  

# 设置lineStyle示范

from  pyecharts import Line

x = ['2018-{:0>2d}'.format(s) for s in range(1,13)]
y1 = [5,10,26,30,35,30,20,26,40,46,40,50]
y2 = [8,20,24,36,40,36,40,45,50,53,48,58]

line = Line(title = "月销售总额",width = 600,height = 420)

line.add(name = "商家A", x_axis = x, y_axis = y1,
         #
         #=====设置lineStyle=====
         line_width = 2,
         line_opacity = 0.5, # 透明度
         line_color = 'red'
        )
line.add(name = "商家B", x_axis = x, y_axis = y2,
         #
         #=====设置xyAxis=====
         is_xaxis_boundarygap = False,  # x坐标刻度对准数据,而不是作为分类边界
         #
         #=====设置dataZoom=====
         is_datazoom_show = True, #显示 dataZoom控制条
         #
         #=====设置lineStyle=====
         line_width = 3,
         line_color = '#11ffbb',
         line_type = 'dashed', # 线型,可以是solid,dashed,或者dotted
        )
line

  

# 设置markPoint和markLine示范

from  pyecharts import Line

x = ['2018-{:0>2d}'.format(s) for s in range(1,13)]
y1 = [5,10,26,30,35,30,20,26,40,46,40,50]
y2 = [8,20,24,36,40,36,40,45,50,53,48,58]

line = Line(title = "月销售总额",width = 600,height = 420)

line.add(name = "商家A", x_axis = x, y_axis = y1,
         #
         #=====设置lineStyle=====
         line_width = 2,
         line_opacity = 0.5, # 透明度
         line_color = 'red',
         #
         #=====设置markPoint&markLine=====
         mark_point = ['min','max'], #标记点
         mark_line = ['average'] #标记线
        )
line.add(name = "商家B", x_axis = x, y_axis = y2,
         #
         #=====设置xyAxis=====
         is_xaxis_boundarygap = False,  # x坐标刻度对准数据,而不是作为分类边界
         yaxis_min = 0,yaxis_max = 100,  # 设置y坐标轴刻度范围
         #
         #=====设置dataZoom=====
         is_datazoom_show = True, #显示 dataZoom控制条
         #
         #=====设置lineStyle=====
         line_width = 3,
         line_type = 'dashed', # 线型,可以是solid,dashed,或者dotted

         #=====设置markPoint&markLine=====
         mark_point = [{"coord": ['2018-09', 60], "name": "2018/09销售目标"}, 
          {"coord": ['2018-11', 80], "name": "2018/10销售目标"}]  # 自定义标记点
        )
line

  

If you need to repeatedly use the same configuration, Style class may be used to simplify the process.

 

from pyecharts import Pie,Style

pie = Pie('各类电影中"好片"所占的比例', "数据来自豆瓣", title_pos='center')
style = Style()
pie_style = style.add(
    label_pos="center",
    is_label_show=True,
    label_text_color=None
)

pie.add(
    "", ["剧情", ""], [25, 75], center=[10, 30], radius=[18, 24], **pie_style
)
pie.add(
    "", ["奇幻", ""], [24, 76], center=[30, 30], radius=[18, 24], **pie_style
)
pie.add(
    "", ["爱情", ""], [14, 86], center=[50, 30], radius=[18, 24], **pie_style
)
pie.add(
    "", ["惊悚", ""], [11, 89], center=[70, 30], radius=[18, 24], **pie_style
)
pie.add(
    "", ["冒险", ""], [27, 73], center=[90, 30], radius=[18, 24], **pie_style
)
pie.add(
    "", ["动作", ""], [15, 85], center=[10, 70], radius=[18, 24], **pie_style
)
pie.add(
    "", ["喜剧", ""], [54, 46], center=[30, 70], radius=[18, 24], **pie_style
)
pie.add(
    "", ["科幻", ""], [26, 74], center=[50, 70], radius=[18, 24], **pie_style
)
pie.add(
    "", ["悬疑", ""], [25, 75], center=[70, 70], radius=[18, 24], **pie_style
)
pie.add(
    "", ["犯罪", ""],[28, 72],center=[90, 70], radius=[18, 24], legend_top="bottom", 
    **pie_style
)
pie

  

Third, the combination chart

 

Red: These examples show you the chart above configuration I basically get to, simply put, is that we can modify the chart theme, chart configuration common property, as well as configure specific element properties, find the corresponding examples with reference to change it. But sometimes I want a number of different types of charts drawn on a map, such as bar charts and line charts at the same time drawing on a graph, draw a chart that contains multiple sub-graphs, pyecharts can do it?

 

Xiao Ming: Of course myself. pyecharts can use a combination of multiple basic chart charts processed into content richer, more expressive combination chart. In pyecharts to graphically combined in the main: Grid, Overlap, Page, Timeline of these four ways.

 

1, Grid compositions charts

 

Grid compositions charts can be displayed in parallel various figures, similar effect subgraph. Grid subgraph may be Overlap.

 

from pyecharts import Bar, Line, Grid

x = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
y1 = [5, 20, 36, 10, 75, 90]
y2 = [10, 25, 8, 60, 20, 80]
bar = Bar("柱状图示例", height=720)
bar.add("商家A", x, y1, is_stack=True)
bar.add("商家B", x, y2, is_stack=True)


line = Line("折线图示例", title_top="50%")
x = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
line.add(
    "最高气温",
    x,
    [11, 11, 15, 13, 12, 13, 10],
    mark_point=["max", "min"],
    mark_line=["average"],
)
line.add(
    "最低气温",
    x,
    [1, -2, 2, 5, 3, 2, 0],
    mark_point=["max", "min"],
    mark_line=["average"],
    legend_top="50%",
)

grid = Grid()
#利用grid_bottom,grid_top,grid_left,grid_right四个参数控制子图的相对位置
grid.add(bar, grid_bottom="60%")  
grid.add(line, grid_top="60%")
grid

 

Grid dataZoom solution using the X-axis with overlapping labels

 

from pyecharts import Bar, Grid

x = [
    "2019-01-01",
    "2019-01-02",
    "2019-01-03",
    "2019-01-04",
    "2019-01-05",
    "2019-01-06",
    "2019-01-07",
    "2019-01-08",
    "2019-01-09",
]
y = [10, 20, 30, 40, 50, 60, 70, 80, 90]

grid = Grid()
bar = Bar("利用 Grid 解决 dataZoom 与 X 轴标签重叠问题")
bar.add("", x, y, is_datazoom_show=True, xaxis_interval=0, xaxis_rotate=30)

# 把 bar 加入到 grid 中,并适当调整 grid_bottom 参数,使 bar 图整体上移
grid.add(bar, grid_bottom="25%")

  

2, Overlap compositions charts

 

Overlap Chart combination may be different types of charts drawn on the same graph.

 

from pyecharts import Bar, Line, Overlap

attr = ['A', 'B', 'C', 'D', 'E', 'F']
v1 = [10, 20, 30, 40, 50, 60]
v2 = [38, 28, 58, 48, 78, 68]
bar = Bar("Line - Bar 示例")
bar.add("bar", attr, v1)
line = Line()
line.add("line", attr, v2)

overlap = Overlap()
overlap.add(bar)
overlap.add(line)
overlap

 

Overlap and a double axis

 

from pyecharts import Line, Bar, Overlap

attr = ["{}月".format(i) for i in range(1, 13)]
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.2, 48.7, 18.8, 6.0, 2.3]
v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]

bar = Bar()
bar.add("蒸发量", attr, v1)
bar.add("降水量", attr, v2, yaxis_formatter=" ml",
        yaxis_interval=50, yaxis_max=250)

line = Line()
line.add("平均温度", attr, v3, yaxis_formatter=" °C", yaxis_interval=5)

overlap = Overlap(width=800, height=500)
# 默认不新增 x y 轴,并且 x y 轴的索引都为 0
overlap.add(bar)
# 新增一个 y 轴,此时 y 轴的数量为 2,第二个 y 轴的索引为 1(索引从 0 开始),所以设置 yaxis_index = 1
# 由于使用的是同一个 x 轴,所以 x 轴部分不用做出改变
overlap.add(line, yaxis_index=1, is_add_yaxis=True)
overlap

  

3, Pages compositions charts

 

Pages can be more than one chart in order to show a web page, suitable for production of graphical reports. Pages may be a chart Grid, Overlap or Timeline.

 

 

from pyecharts import Bar, Scatter3D
from pyecharts import Page

page = Page()         

# bar
attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
v1 = [5, 20, 36, 10, 75, 90]
v2 = [10, 25, 8, 60, 20, 80]
bar = Bar("柱状图数据堆叠示例",width = 500,height = 300)
bar.add("商家A", attr, v1, is_stack=True)
bar.add("商家B", attr, v2, is_stack=True)
page.add(bar)         

# scatter3D
import random
data = [
    [random.randint(0, 100),
    random.randint(0, 100),
    random.randint(0, 100)] for _ in range(80)
]
range_color = [
    '#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf',
    '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
scatter3D = Scatter3D("3D 散点图示例", width= 500, height=300)
scatter3D.add("", data, is_visualmap=True, visual_range_color=range_color)

page.add(scatter3D)  

page

  

4, Timeline compositions charts

 

Timeline multiple charts can be animated.

 

from pyecharts import Bar, Timeline
from random import randint

attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
bar_1 = Bar("2012 年销量", "数据纯属虚构")
bar_1.add("春季", attr, [randint(10, 100) for _ in range(6)])
bar_1.add("夏季", attr, [randint(10, 100) for _ in range(6)])
bar_1.add("秋季", attr, [randint(10, 100) for _ in range(6)])
bar_1.add("冬季", attr, [randint(10, 100) for _ in range(6)])

bar_2 = Bar("2013 年销量", "数据纯属虚构")
bar_2.add("春季", attr, [randint(10, 100) for _ in range(6)])
bar_2.add("夏季", attr, [randint(10, 100) for _ in range(6)])
bar_2.add("秋季", attr, [randint(10, 100) for _ in range(6)])
bar_2.add("冬季", attr, [randint(10, 100) for _ in range(6)])

bar_3 = Bar("2014 年销量", "数据纯属虚构")
bar_3.add("春季", attr, [randint(10, 100) for _ in range(6)])
bar_3.add("夏季", attr, [randint(10, 100) for _ in range(6)])
bar_3.add("秋季", attr, [randint(10, 100) for _ in range(6)])
bar_3.add("冬季", attr, [randint(10, 100) for _ in range(6)])

bar_4 = Bar("2015 年销量", "数据纯属虚构")
bar_4.add("春季", attr, [randint(10, 100) for _ in range(6)])
bar_4.add("夏季", attr, [randint(10, 100) for _ in range(6)])
bar_4.add("秋季", attr, [randint(10, 100) for _ in range(6)])
bar_4.add("冬季", attr, [randint(10, 100) for _ in range(6)])

bar_5 = Bar("2016 年销量", "数据纯属虚构")
bar_5.add("春季", attr, [randint(10, 100) for _ in range(6)])
bar_5.add("夏季", attr, [randint(10, 100) for _ in range(6)])
bar_5.add("秋季", attr, [randint(10, 100) for _ in range(6)])
bar_5.add("冬季", attr, [randint(10, 100) for _ in range(6)], is_legend_show=True)

timeline = Timeline(is_auto_play=True,
                    timeline_bottom=0,
                    timeline_play_interval=800  # 每800ms播放一张
                   )

timeline.add(bar_1, '2012 年')
timeline.add(bar_2, '2013 年')
timeline.add(bar_3, '2014 年')
timeline.add(bar_4, '2015 年')
timeline.add(bar_5, '2016 年')
timeline

 

Guess you like

Origin www.cnblogs.com/yinguo/p/11223265.html