又一个可视化神器 Highcharts,Python版!

Python那些事 3天前

以下文章来源于Python数据之道 ,作者投稿君

来源:Python数据之道
作者:Peter,整理:Lemon

本文重点介绍的是可视化库 Highcharts 的相关基础知识,以及如何利用Highcharts来绘制不同场景和需求下的精美柱状图,主要内容包含:

  • Highcharts简介
  • Highcharts有多强
  • Highcharts 4大利器
  • python-highcharts使用
  • 绘制精美柱状图

Highcharts简介

什么是Highcharts

首先看一段来自官网的赞美:

Make your data come alive。Highcharts makes it easy for developers to set up interactive charts in their web pages.

Highcharts 是一个用纯 JavaScript 编写的图表库,它能够很简单便捷的在 web 网站或者是web 应用程序中添加有交互性质的图表。

Highcharts 是免费提供给个人学习、个人网站和非商业用途的使用的。

中文官网地址:https://www.highcharts.com.cn/

Highcharts特性

Highcharts 具备诸多特性,以至于它大受欢迎:

  • 兼容性:支持所有主流的浏览器和移动平台(iOS、Android等)
  • 多设备:支持多种设备,如手持设备、平板等
  • 免费使用:能够供个人免费学习使用
  • 配置简单:Highcharts中的数据全部配置成json格式
  • 动态多维图表:Highcharts中生成的图表能够修改,同时支持多维图表
  • 导出格式多样:能够导出PDF/PNG/JPG/SVG等多种格式
  • 可变焦:选中图表部分放大,能够近距离观察图表

上面仅仅是列出了Highcharts的部分特性,它还有时间轴上的时间精确到毫秒、文字可在任意方向旋转等特性。

Highcharts有多强

Highcharts 有上面列举的诸多特性,所以它受到了国内外很多大公司的青睐,从它的官网上看到很多知名的企业,比如:Facebook、Twitter、Yahoo、IBM、阿里云等

Highcharts 4大利器

Highcharts之所以如此强大,主要是因为它有4大利器:

  • Highcharts
  • Highcharts Stock
  • Highcharts Maps
  • Highcharts Gantt

Highcharts

方便快捷的纯 JavaScript 交互性图表。可以说,Highcharts 是目前市面上最简单灵活的图表库

Highcharts Stock

方便快捷地创建股票图、大数据量的时间轴图表。

Highstock 是用纯 JavaScript 编写的股票图表控件,可以用来开发股票走势图及大数据量时间轴图表。

Highcharts Maps

非常优秀的HTML5地图组件,支持下钻、触摸、手势等操作。

Highmaps 继承了 Highcharts 简单易用的特性。利用它可以方便快捷的创建用于展示销售、选举结果等其他与地理位置关系密切的交互地图图表。

Highcharts Gantt

最简单好用的JavaScript 甘特图库。

方便易用的交互式甘特图,可以用于展示时间分配、任务调度、事件及资源使用情况。

python-highcharts使用

安装python-highcharts

开头笔者提到过:Highcharts 是基于 JavaScript 编写的图表库。

因为很多人并不是很擅长前端语言,所以有位大神编写出来基于 Python 的第三方的库:python-highcharts,详细说明见github https://github.com/kyper-data/python-highcharts

安装 python-highcharts 非常的简单:

pip install python-highcharts

目前 python-highcharts 支持 Python2.7/3.4+python版本需要满足需求

使用demo

安装好 python-highcharts 之后,我们用一个小案例来说明如何通过它绘制图形,首先看看整体的代码和图形:

# 1-导入库和实例化from highcharts import Highchartchart = Highchart()

# 2-配置项设置options = {    'chart': {        'inverted': True  # 翻转x轴和y轴    },    'title': {  # 主标题        'text': 'Atmosphere Temperature by Altitude'    },    'subtitle': {  # 副标题        'text': 'According to the Standard Atmosphere Model'    },    'xAxis': {  # x轴设置        'reversed': False,        'title': {            'enabled': True,            'text': 'Altitude'        },        'labels': {            'formatter': 'function () {\                return this.value + "km";\            }'        },        'maxPadding': 0.05,        'showLastLabel': True    },    'yAxis': {  # y轴设置        'title': {            'text': 'Temperature'        },        'labels': {            'formatter': "function () {\                return this.value + '°';\            }"        },        'lineWidth': 2    },    'legend': {  # 图例设置        'enabled': False    },    'tooltip': {  # 提示工具设置        'headerFormat': '<b>{series.name}</b><br/>',        'pointFormat': '{point.x} km: {point.y}°C'    }}

# 3-实例化对象中添加配置chart.set_dict_options(options)

# 4-绘图所需的数据和添加数据data =  [[0, 15],          [10, -50],          [20, -56.5],          [30, -46.5],          [40, -22.1],          [50, -2.5],          [60, -27.7],          [70, -55.7],          [80, -76.5]]# 添加数据chart.add_data_set(data, 'spline', 'Temperature', marker={'enabled': False}) 

# 5-在线绘图chart

通过上面的代码我们可以看到使用 python-highcharts 绘图的5个基本步骤:

  1. 导入库和示例化对象
  2. 设置各种配置项;配置项都是字典形式
  3. 往实例化对象中添加字典形式的配置项
  4. 准备数据和往实例化对象中添加数据,并设置图形的相关信息
  5. notebook中在线绘图

绘制精美柱状图

基础柱状图

from highcharts import Highchart   # 导入库 H = Highchart(width=750, height=600)  # 设置图形的大小

# 4组数据,代表4个年份# 每组5个数据代表的是5个洲data1 = [107, 31, 235, 203, 24]  data2 = [133, 156, 947, 868, 106]data3 = [373, 914, 854, 732, 34]data4 = [652, 954, 1250, 740, 38]

# 进行配置options = {    'chart': {  # 加上chart配置变成水平柱状图        'type': 'bar'    }, 'title': {  # 1、主标题        'text': 'Stacked bar chart'     },

    'subtitle': {   # 2、副标题        'text': 'Source: <a href="https://en.wikipedia.org/wiki/World_population">Wikipedia.org</a>'    },

    'xAxis': {   # 3、横轴的5个分类        'categories': ['Africa', 'America', 'Asia', 'Europe', 'Oceania'],        'title': {            'text': "5个洲"   # x轴的名称        }    },    'yAxis': {        'min': 0,  # 设置最小值        'title': {            'text': '人口数(百万)',  # y轴名称            'align': 'high'        },        'labels': {            'overflow': 'justify'        }    },    'tooltip': {        'valueSuffix': ' millions'    },    'legend': {  # 图例设置        'layout': 'vertical',   # 垂直方向        'align': 'right',  # 靠右显示        'verticalAlign': 'top',   # 顶部        'x': -40,        'y': 80,        'floating': True,        'borderWidth': 2,    # 图例外围线条宽度        'backgroundColor': "((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#9ACFF0')",#图例背景颜色        'shadow': True    },    'credits': {  # 右下角的版权标签        'enabled': True    },    'plotOptions': {        'bar': {            'dataLabels': {                'enabled': True  # 显示数据(柱状图顶部的数据显示出来)            }        }    }}

H.set_dict_options(options)   # 添加配置

# 每个年份添加一组数据H.add_data_set(data1, 'bar', 'Year 2000')H.add_data_set(data2, 'bar', 'Year 2004')H.add_data_set(data3, 'bar', 'Year 2008')H.add_data_set(data4, 'bar', 'Year 2012')

H

蝴蝶柱状图

两个不同类型的双排柱状图:

from highcharts import HighchartH = Highchart(width=550, height=400)

# 1、数值分类区间categories = ['0-4', '5-9', '10-14', '15-19',              '20-24', '25-29', '30-34', '35-39',               '40-44','45-49', '50-54', '55-59',               '60-64', '65-69','70-74', '75-79',               '80-84', '85-89', '90-94','95-99', '100 + ']# 2、配置项# 在这种图形中横轴和纵轴需要调换options = { 'chart': {  #  指定图表类型:柱状图        'type': 'bar'     },    'title': {  # 主标题        'text': 'Population pyramid for Germany, midyear 2010'    },    'subtitle': {  # 副标题        'text': 'Source: www.census.gov'    },    'xAxis': [{  # 左侧标签设置        'categories': categories,        'reversed': False,   # 分类区间是否翻转        'labels': {            'step': 1  # 标签区间的间隔        }    }, {   # 右侧标签设置        'opposite': True,        'reversed': False,        'categories': categories,        'linkedTo': 0,        'labels': {            'step': 1        }    }],    'yAxis': {        'title': {            'text': None        },        'labels': {  # y轴标签            'formatter': "function () {\                                    return (Math.abs(this.value) / 1000000) + 'M';\                                }"        },        'min': -4000000,        'max': 4000000    },

    'plotOptions': {        'series': {            'stacking': 'normal'        }    },

    'tooltip': {        'formatter': "function () {\                            return '<b>' + this.series.name + ', age ' + this.point.category + '</b><br/>' +\                                'Population: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);\                        }"    },}

# 设置男女的数值data_male = [-1746181, -1884428, -2089758, -2222362,             -2537431, -2507081, -2443179, -2664537,              -3556505, -3680231, -3143062, -2721122,              -2229181, -2227768,-2176300, -1329968,              -836804, -354784, -90569, -28367, -3878]

data_female = [1656154, 1787564, 1981671, 2108575,                2403438, 2366003, 2301402, 2519874,               3360596, 3493473, 3050775, 2759560,                2304444, 2426504, 2568938, 1785638,               1447162, 1005011, 330870, 130632, 21208]

# 添加配置项H.set_dict_options(options)

# 添加数据和指定图表类型barH.add_data_set(data_male, 'bar', 'Male')H.add_data_set(data_female, 'bar', 'Female')

H

垂直柱状图

from highcharts import Highchart   # 导入库 H = Highchart(width=800, height=600)  # 设置图形的大小

# 配置数据项data1 = [5, 3, 4, 7, 2]data2 = [2, 2, 3, 2, 1]data3 = [3, 4, 4, 2, 5]

options = {    'chart': {        'type': 'column'   # bar改成column    },    'title': {        'text': 'Stacked column chart'    },    'xAxis': {        'categories': ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']    },    'yAxis': {        'min': 0,        'title': {            'text': 'Total fruit consumption'        },        'stackLabels': {            'enabled': True,            'style': {                'fontWeight': 'bold',                'color': "(Highcharts.defaultOptions.title.style && \                    Highcharts.defaultOptions.title.style.color) || 'gray'"            }        }    },    'legend': {        'align': 'right',        'x': -30,        'verticalAlign': 'top',        'y': 25,        'floating': True,        'backgroundColor':            "Highcharts.defaultOptions.legend.backgroundColor || 'white'",        'borderColor': '#CCC',        'borderWidth': 1,        'shadow': False    },    'tooltip': {        'headerFormat': '<b>{point.x}</b><br/>',        'pointFormat': '{series.name}: {point.y}<br/>Total: {point.stackTotal}'    },    # 在这里设置堆叠的信息    'plotOptions': {   # 将每个数据在柱状图上方显示出来        'column': {            'stacking': 'normal',            'dataLabels': {                'enabled': True  # 显示数据(柱状图顶部的数据显示出来)            }        }    }}

H.set_dict_options(options)   # 添加配置

# 将之前的bar改成column即可H.add_data_set(data1,'column','John')H.add_data_set(data2,'column','Jane')H.add_data_set(data3,'column','Joe')

H

水平叠加柱状图

from highcharts import Highchart   # 导入库 H = Highchart(width=800, height=600)  # 设置图形的大小

# 配置数据项data1 = [5, 3, 4, 7, 2]data2 = [2, 2, 3, 2, 1]data3 = [3, 4, 4, 2, 5]

options = {    'chart': {        'type': 'bar'  # 图表类型    },    'title': {  # 主标题        'text': 'Stacked bar chart'    },    'xAxis': {        'categories': ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']    },    'yAxis': {        'min': 0,        'title': {            'text': 'Total fruit consumption'        }    },    'legend': {        'reversed': True    },    'plotOptions': {        'series': {            'stacking': 'normal'        }    }}

H.set_dict_options(options)   # 添加配置

H.add_data_set(data1,'bar','John')H.add_data_set(data2,'bar','Jane')H.add_data_set(data3,'bar','Joe')

H

带有负值的柱状图

有时候我们的数据中还有负值,利用Highcharts同样可以绘制柱状图:

from highcharts import Highchart   # 导入库 H = Highchart(width=800, height=600)  # 设置图形的大小

# 配置数据项data1 = [5, 3, -4, 7, 2]data2 = [2, 2, 3, -2, 1]data3 = [-3, 4, 4, 2, 5]

options = {    'chart': {  # 图表类型不是bar,而是column        'type': 'column'      },    'title': {  # 主标题        'text': 'column with negative values'    },    'xAxis': {        'categories': ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']    },    'yAxis': {        'title': {            'text': '水果数量',  # y轴名称            'align': 'high'        },        'labels': {            'overflow': 'justify'        }    },    'legend': {        'reversed': True    },    'credits': {  # 右下角的版权信息        'enabled': False    },    'plotOptions': {   # 将每个数据在柱状图上方显示出来        'bar': {            'dataLabels': {                'enabled': True  # 显示数据(柱状图顶部的数据显示出来)            }        }    } }

H.set_dict_options(options)   # 添加配置H.add_data_set(data1,'bar','John')H.add_data_set(data2,'bar','Jane')H.add_data_set(data3,'bar','Joe')

H

带有百分比的柱状图

from highcharts import Highchart   # 导入库 H = Highchart(width=800, height=600)  # 设置图形的大小

# 配置数据项data1 = [5, 3, 4, 7, 2]data2 = [2, 2, 3, 2, 1]data3 = [3, 4, 4, 2, 5]

options = {    'chart': {        'type': 'column'  # 图表类型    },    'title': {  # 主标题        'text': '带有百分比的柱状图'    },    'xAxis': {        'categories': ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']    },    'yAxis': {        'min': 0,        'title': {            'text': 'Total fruit consumption'        }    },    'tooltip': {        'pointFormat': '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',        'shared': True    },    'legend': {        'reversed': True    },    'plotOptions': {        'series': {   # 将stacking参数设置成percent            'stacking': 'percent'   # 多种取值:normal+percent        }    }}

H.set_dict_options(options)   # 添加配置

H.add_data_set(data1,'bar','John')H.add_data_set(data2,'bar','Jane')H.add_data_set(data3,'bar','Joe')

H

坐标属性倾斜的柱状图

当我们的坐标属性过长的时候,属性值显示在坐标轴上可以倾斜一定的角度:

from highcharts import Highchart   # 导入库 H = Highchart(width=800, height=600)  # 设置图形的大小

data = [        ['Shanghai', 24.2],        ['Beijing', 20.8],        ['Karachi', 14.9],        ['Shenzhen', 13.7],        ['Guangzhou', 13.1],        ['Istanbul', 12.7],        ['Mumbai', 12.4],        ['Moscow', 12.2],        ['São Paulo', 12.0],        ['Delhi', 11.7],        ['Kinshasa', 11.5],        ['Tianjin', 11.2],        ['Lahore', 11.1],        ['Jakarta', 10.6],        ['Dongguan', 10.6],        ['Lagos', 10.6],        ['Bengaluru', 10.3],        ['Seoul', 9.8],        ['Foshan', 9.3],        ['Tokyo', 9.3]    ]

options = {    'chart': {        'type': 'column'    },    'title': {        'text': '2017年度世界大城市'    },    'subtitle': {   # 带上了url地址,点击进入链接的文章中        'text': '来源: <a href="http://en.wikipedia.org/wiki/List_of_cities_proper_by_population">维基百科</a>'    },    'xAxis': {        'type': 'category',        'labels': {            'rotation': -45,   # 控制倾斜方向:+ 表示向右倾斜            'style': {                'fontSize': '12px',  # 字体设置                'fontFamily': 'Verdana, sans-serif'            }        }    },    'yAxis': {        'min': 0,        'title': {            'text': '人口数(百万)',#             'rotation': -1,#             'style': {#                 'fontSize': '13px',#                 'fontFamily': 'Verdana, sans-serif'#             }        }    },

    'legend': {        'enabled': False    },

    'tooltip': {   # 当鼠标放到柱子上去的时候显示的内容        'pointFormat': 'Population in 2017: <b>{point.y:.1f} millions</b>'    },

    # 重要设置项    'plotOptions': {   # 将每个数据在柱状图上方显示出来        'column': {            'stacking': 'normal',            'dataLabels': {                'enabled': True,                'inside': False,                'rotation': -1,                'color': '#FFFFFF',#                 'align': 'left',                'format': '{point.y:.1f}',                 'y': 10,   # 10 pixels down from the top#                 'style': {#                     'fontSize': '15px',#                     'fontFamily': 'Verdana, sans-serif'#                 }            }        }    }}

H.set_dict_options(options)   # 添加配置

H.add_data_set(data,'column','Population')

H

基于最值的柱状图

通过最小值和最大值可以绘制在区间内变化的柱状图:

from highcharts import Highchart   # 导入库 H = Highchart(width=800, height=600)  # 设置图形的大小

data_range = [        [-9.9, 10.3],        [-8.6, 8.5],        [-10.2, 11.8],        [-1.7, 12.2],        [-0.6, 23.1],        [3.7, 25.4],        [6.0, 26.2],        [6.7, 21.4],        [3.5, 19.5],        [-1.3, 16.0],        [-8.7, 9.4],        [-9.0, 8.6]        ]

options = {    'chart': {        'type': 'columnrange',        'inverted': True    },

#     # Note: Prefer using linkedDescription or caption instead.#     'accessibility': {   # 取消了该属性#         'description': 'Image description'#     },

    'title': {        'text': 'title'    },

    'subtitle': {        'text': 'subtitle'    },

    'xAxis': {        'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']    },

    'yAxis': {        'title': {            'text': 'Temperature ( °C )'        }    },

    'tooltip': {        'valueSuffix': '°C'    },    'legend': {        'enabled': False    },    'plotOptions': {        'columnrange': {            'dataLabels': {                'enabled': True,                'format': '{y}°C'            }        }    }}

H.set_dict_options(options)   # 添加配置

H.add_data_set(data_range,'columnrange','Temperatures')  # 添加数据

H

多轴柱状图

有时候可以将多个图形放在一个画布中:

from highcharts import HighchartH = Highchart(width=850, height=400)

# 3组不同的数据:降雨量、气压、温度data1 = [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]data2 = [1016, 1016, 1015.9, 1015.5, 1012.3, 1009.5, 1009.6, 1010.2, 1013.1, 1016.9, 1018.2, 1016.7]data3 = [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]

options = { 'chart': {          'zoomType': 'xy'  # xy缩放变化    },    'title': {  # 标题设置        'text': 'Average Monthly Weather Data for Tokyo'    },    'subtitle': {        'text': 'Source: WorldClimate.com'    },    'xAxis': [{  # x轴数据        'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],        'crosshair': True   # True 表示启用竖直方向的十字准星;[true, true] 启动横纵两个轴    }],

    # y轴有3个属性设置    'yAxis': [   # 列表中3个元素:温度、降雨量、气压        # 1-温度        { 'labels': {            'format': '{value}°C',  #  温度数据的单位设置            'style': {                'color': 'Highcharts.getOptions().colors[2]'  # 索引为2,取出第3个图                    }                },                 'title': {                    'text': 'Temperature',  # 名字设置                    'style': {                        'color': 'Highcharts.getOptions().colors[2]'                            }                        },                 'opposite': True  # 纵坐标默认在左边,”相反opposite“取右边的位置        },           # 2-降雨量        { 'labels': {              'format': '{value} mm',  # 单位设置            'style': {                'color': 'Highcharts.getOptions().colors[0]'                    }                },        'gridLineWidth': 0,   # 线宽(水平方向的灰色线条)        'title': {            'text': 'Rainfall',   # 名字设置            'style': {                'color': 'Highcharts.getOptions().colors[0]'                    }                }        },        # 3-气压        {'labels': {  # 海平面气压数据            'format': '{value} mb',            'style': {                'color': 'Highcharts.getOptions().colors[1]'                    }                },        'opposite': True,   # 纵坐标右侧显示        'gridLineWidth': 0,        'title': {            'text': 'Sea-Level Pressure',  # 纵轴标题名字设置            'style': {                'color': 'Highcharts.getOptions().colors[1]'                    }                }        }    ],    'tooltip': {   # 数据提示框,鼠标放上去显示3个坐标的数据        'shared': True,

    },    'legend': {        'layout': 'vertical',  # 图例垂直显示;horizontal水平显示(并排)        'align': 'left',  # 图例靠左        'x': 80,  # 图例到y轴距离        'verticalAlign': 'top',        'y': 55,  # 图例到x轴距离        'floating': True,  # 图例是否可以显示在图形:False表示图例和图形完全分开        'backgroundColor': "(Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'"  # 图例背景色    },}H.set_dict_options(options)

# 如何绘制多个图形# 设置项options中3者顺序:温度(0)、降雨量(1)、气压(2)# 添加的数据化顺序和坐标轴的顺序要保持一致

H.add_data_set(data1,  # 添加数据(降雨量)-colors[0]               'column',  # 指定图形类型:柱状图               'Rainfall', # 名称               yAxis=1,                tooltip={                   'valueSuffix': ' mm'  # 提示数据的单位               })

H.add_data_set(data2,  # 气压-colors[1]               'spline',  # spline表示圆滑的曲线;line表示折线               'Sea-Level Pressure',                yAxis=2 ,               marker={                   'enabled': True   # 标记:F表示虚点;T表示实点               },               dashStyle='shortdot',  #  在图形中直接显示markder;设置成False则需要鼠标放上去才会出现markder点               tooltip={                'valueSuffix': ' mb'                 })H.add_data_set(data3,  # 温度-colors[2]               'spline',                'Temperature',               yAxis=0,               tooltip={                'valueSuffix': ' °C'               })

H

总结

本文中我们简单的介绍了可视化库 Highcharts 的主要特点和4大利器,同时通过 python-highcharts 绘制了多个柱状图的案例,我们可以看到:

  • Highcharts 的确是非常的强大;如果读者能够很好地掌握前端语言 JavaScript,可以更加灵活地使用 Highcharts
  • 在利用 python-highcharts 进行绘图的过程中,步骤非常清晰(5个步骤),重点是要掌握配置项的设置
  • Higcharts 能够满足不同需求下的绘制,绘制的图形动态效果非常明显。

作者简介

Peter,硕士毕业僧一枚,从电子专业自学Python入门数据行业,擅长数据分析及可视化。喜欢数据,坚持跑步,热爱阅读,乐观生活。个人格言:不浮于世,不负于己

(完)看完本文有收获?请转发分享给更多人关注「Python那些事」,做全栈开发工程师点「在看」的人都变好看了哦
不看的原因确定内容质量低不看此公众号
(0)

相关推荐