整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

用 Highcharts 绘制饼图,也很强大

用 Highcharts 绘制饼图,也很强大

源:Python数据之道

作者:Peter

整理:阳哥

用 Highcharts 绘制饼图,也很强大

前不久,阳哥在「Python数据之道」分享了读者投稿的文章,较为综合的介绍了可视化库 Highcharts ,这个一个 JavaScript 下的可视化工具,同时也有 Python 版本。前文链接如下:

  • 又一个可视化神器Highcharts,Python版也有哦!

不少同学对这个工具感兴趣,今天来跟大家介绍下如何用这个工具来绘制饼图。大家可以对照自己常用的 Python 库,看看哪些工具更适合自己。

本文中介绍的是如何利用 python-highcharts 绘制各种饼图来满足不同的需求,主要包含:

  • 基础饼图
  • 单色+多色饼图制作
  • 带上图例+数据的饼图
  • 双层饼图的制作
  • 扇形饼图

基础饼图

首先我们看看整体的效果:

  • 可以很清晰地看到每个区块的名字
  • 当我们的光标移动到某个区块,能够看到该区块占的比例

整理的代码如下:

单色+多色饼图

上面的基础饼图在 Highcharts 中默认是每个区块的颜色是各不相同的,如果我们想每个区块的颜色是相同的,或者某几个区块的颜色是相同的,该如何操作呢?

单色饼图

首先看看整体的效果图:

整体的代码如下:从导入库到数据的添加设置、以及参数项的配置等

其中,重点的参数设置看这里:

Highcharts 中就是通过 Highcharts.getOptions().colors 来设置默认的颜色。我们改变下设置,绘制另一种颜色的饼图:

多色饼图

如果我们想某几个区块显示相同的颜色,可以设置相同的数值,首先看看具体的效果图:

可以看到我们将6个区块的颜色分成了3大类,就是通过上面的方法来实现的。如果我们设置成0-5的数值,即每个区块的颜色各不相同,那么就是基础饼图的样子:

显示图例和数据的饼图

上面提到的各种饼图都是没有图例的,同时在区块中也没有直接显示原始数据,下面介绍方法来实现这两种效果:

图例和数据显示的代码设置:

双层饼图

上面介绍了各种单个饼图的制作,下面讲解如何利用 python-highcharts 制作双层饼图。看看整体的效果:

从上图中我们可以看到:主要是有5种颜色

  • 蓝色
  • 黑色
  • 绿色
  • 红色
  • 紫色

数据中显示每个大类中还有子类,比如:MSIE 父类中还有子类 MSIE6.0、MSIE7.0、MSIE8.0、MSIE9.0。现在我们看看代码中数据的显示:

可以很清晰地看到:先显示父级的数据,再显示子级的数据。整体的代码如下:

扇形图

上面介绍的都是如何制作各种饼图,下面介绍一种制作 扇形图 的方法。首先看看整体的效果:

上面显示了5个类别的数据,同时显示了图例,并且在扇形图中显示了数据。整体的代码如下:

重点的设置部分:

总结

本文结合各种实际案例介绍了如何利用 python-highcharts 来绘制各种不同需求的饼图或者扇形图。通过上面案例的介绍,我们发现使用 Highcharts 绘制图形的主要步骤如下:

  1. 导入我们需要的 Highcharts 库,再实例化一个 Highcharts 对象
  2. 数据项的配置:在绘图的时候,数据的配置也很重要。Highcharts中对数据格式要求还是挺高的,而且在数据中还可以对数据进行效果的设置
  3. 图形参数设置:这是整个绘图过程中 最为重要 的部分,主要是包含:图表类型chart(柱状图、饼图、折线图等)、标题title(主标题、副标题)、数据提示工具tooltip、绘图选型plotOptions等配置项的设置
  4. 添加数据项和配置项。在添加配置项的时候,我们可以对最终的图形进行一些效果设置。

最后是个人的一点感觉:利用 Highcharts 来进行绘图的确代码量很大,基本上画一个简单的饼图或者柱状图都需要大量的代码(相对其他自己使用的可视化库,比如 pyecharts、plotly_express 等)。

但是它的强大之处,应该是在于结合前端的知识,绘制更多动态效果的图形,让图形的可视化效果更美观

是python画图系列第三篇--饼图

画饼图用到的方法为:

matplotlib.pyplot.pie()

参数为:

pie(x, explode=None, labels=None,
 colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'),
 autopct=None, pctdistance=0.6, shadow=False,
 labeldistance=1.1, startangle=None, radius=None,
 counterclock=True, wedgeprops=None, textprops=None,
 center=(0, 0), frame=False )

参数说明:

x (每一块)的比例,如果sum(x) > 1会使用sum(x)归一化

labels (每一块)饼图外侧显示的说明文字

explode (每一块)离开中心距离

startangle 起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起

shadow 是否阴影

labeldistance label绘制位置,相对于半径的比例, 如<1则绘制在饼图内侧

autopct 控制饼图内百分比设置,可以使用format字符串或者format function

'%1.1f'指小数点前后位数(没有用空格补齐)

pctdistance 类似于labeldistance,指定autopct的位置刻度

radius 控制饼图半径

返回值:

如果没有设置autopct,返回(patches, texts)

如果设置autopct,返回(patches, texts, autotexts)

patches -- list --matplotlib.patches.Wedge对象

texts autotexts -- matplotlib.text.Text对象

下面是一个简单的示例:

# -*- coding: utf-8 -*-
import numpy as np 
import matplotlib.mlab as mlab 
import matplotlib.pyplot as plt 
labels=['China','Swiss','USA','UK','Laos','Spain']
X=[222,42,455,664,454,334] 
 
fig=plt.figure()
plt.pie(X,labels=labels,autopct='%1.2f%%') #画饼图(数据,数据对应的标签,百分数保留两位小数点)
plt.title("Pie chart")
 
 
plt.show() 
plt.savefig("PieChart.jpg")

下面是结果:

下面是另一个示例:

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
 
def draw_pie(labels,quants):
 # make a square figure
 plt.figure(1, figsize=(6,6))
 # For China, make the piece explode a bit
 expl=[0,0.1,0,0,0,0,0,0,0,0] #第二块即China离开圆心0.1
 # Colors used. Recycle if not enough.
 colors=["blue","red","coral","green","yellow","orange"] #设置颜色(循环显示)
 # Pie Plot
 # autopct: format of "percent" string;百分数格式
 plt.pie(quants, explode=expl, colors=colors, labels=labels, autopct='%1.1f%%',pctdistance=0.8, shadow=True)
 plt.title('Top 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5})
 plt.show()
 plt.savefig("pie.jpg")
 plt.close()
 
# quants: GDP
 
# labels: country name
 
labels=['USA', 'China', 'India', 'Japan', 'Germany', 'Russia', 'Brazil', 'UK', 'France', 'Italy']
 
quants=[15094025.0, 11299967.0, 4457784.0, 4440376.0, 3099080.0, 2383402.0, 2293954.0, 2260803.0, 2217900.0, 1846950.0]
 
draw_pie(labels,quants)

官方文档:

链接:http://matplotlib.org/api/pyplot_api.html

matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)Plot a pie chart.

Call signature:

pie(x, explode=None, labels=None,
 colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'),
 autopct=None, pctdistance=0.6, shadow=False,
 labeldistance=1.1, startangle=None, radius=None,
 counterclock=True, wedgeprops=None, textprops=None,
 center=(0, 0), frame=False )

Make a pie chart of array x. The fractional area of each wedge is given by x/sum(x). If sum(x) <=1, then the values of x give the fractional area directly and the array will not be normalized. The wedges are plotted counterclockwise, by default starting from the x-axis.

Keyword arguments:

explode: [ None | len(x) sequence ]

If not None, is a len(x) array which specifies the fraction of the radius with which to offset each wedge.

colors: [ None | color sequence ]

A sequence of matplotlib color args through which the pie chart will cycle.

labels: [ None | len(x) sequence of strings ]

A sequence of strings providing the labels for each wedge

autopct: [ None | format string | format function ]

If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt%pct. If it is a function, it will be called.

pctdistance: scalar

The ratio between the center of each pie slice and the start of the text generated by autopct. Ignored if autopct is None; default is 0.6.

labeldistance: scalar

The radial distance at which the pie labels are drawn

shadow: [ False | True ]

Draw a shadow beneath the pie.

startangle: [ None | Offset angle ]

If not None, rotates the start of the pie chart by angle degrees counterclockwise from the x-axis.

radius: [ None | scalar ] The radius of the pie, if radius is None it will be set to 1.

counterclock: [ False | True ]

Specify fractions direction, clockwise or counterclockwise.

wedgeprops: [ None | dict of key value pairs ]

Dict of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops={ ‘linewidth’ : 3 } to set the width of the wedge border lines equal to 3. For more details, look at the doc/arguments of the wedge object. By default clip_on=False.

textprops: [ None | dict of key value pairs ]

Dict of arguments to pass to the text objects.

center: [ (0,0) | sequence of 2 scalars ] Center position of the chart.

frame: [ False | True ]

Plot axes frame with the chart.

The pie chart will probably look best if the figure and axes are square, or the Axes aspect is equal. e.g.:

figure(figsize=(8,8))
ax=axes([0.1, 0.1, 0.8, 0.8])

or:

axes(aspect=1)

Return value:

If autopct is None, return the tuple (patches, texts):

  • patches is a sequence of matplotlib.patches.Wedge instances
  • texts is a list of the label matplotlib.text.Text instances.

If autopct is not None, return the tuple (patches, texts, autotexts), where patches and texts are as above, and autotexts is a list of Textinstances for the numeric labels.

Notes

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments are replaced by data[<arg>]:

  • All arguments with the following names: ‘colors’, ‘x’, ‘explode’, ‘labels’.

Additional kwargs: hold=[True|False] overrides default hold state


之前已经发布了三篇Typora代码绘图的文章,如下:

1、Typora笔记之绘图综述

2、Typora笔记之绘制流程图详述(一)

3、Typora笔记之绘制流程图详述(二)

本文接着对Typora通过mermaid插件实现代码绘制饼图进行详细介绍,希望能对感兴趣的朋友有所帮助。

注:原计划接下来是应该写代码绘制序列图的,但粗略地过了一下,要写的内容不少,鉴于之前撰写第三篇文章耗时过长,于是第四篇文章就先选个比较简单的代码绘制饼图了。

本次分享的内容目录如下:

前言

饼图简介

mermaid简介

Typora绘制饼图简介

Typora绘制饼图语法及说明

样例

结束语

参考资料


1. 饼图简介


大家对于饼图想必已经是非常熟悉了,不过为了文章的完整性,这里再做个简单回顾。

饼图Pie Chart),亦称饼状图,是一个划分为几个扇形的圆形统计图表,用于描述量、频率或百分比之间的相对关系。在饼图中,每个扇区的弧长(以及圆心角和面积)大小为其所表示的数量的比例。这些扇区合在一起刚好是一个完全的圆形。顾名思义,这些扇区拼成了一个切开的饼形图案。 —— 来自维基百科



2. mermaid简介


mermaid是一款免费开源的,能在浏览器和终端中运行的特定类型图DSL和SVG渲染器,可以通过DSL(图的文本表示)来绘制简单的SVG图。当前版本的mermaid已经支持多种特定类型图,包括:流程图(Flow Chart)、序列图(Sequence Diagram)、类图(Class Diagram))、状态图(State Diagram)、实体关系图(Entity Relationship Diagram)、用户旅程图(User Journey Diagram)、甘特图(Gantt Diagram)、饼图(Pie Chart)、Git图(Git Graph)等。

使用mermaid通过代码绘制图非常简单,原理是将mermaid代码(Plain Text)通过渲染器(Mermaid JavaScript Library)来转化成图(Graphs, Gantt Charts, and many other Diagrams)并显示。


目前使用mermaid实现代码绘图有以下三种方法:

(一)使用mermaid Live Editor:(网址:https://mermaid-js.github.io/mermaid-live-editor/)

如下图示,在左上侧的Code区编辑修改mermaid代码,右侧的Preview区就会实时显示出经渲染后的图;在右下侧,还能将渲染后的图直接下载成svg或png格式的图片等。


(二)用HTML调用mermaid渲染器

大多数网络浏览器(例如Firefox,Chrome和Safari)都可以渲染mermaid,所以可以直接在html文件中添加mermaid代码,这样在打开html文件时浏览器就会直接完成mermaid的渲染工作,显示出相应图。

示例代码(MermaidHtmlTest.html):

浏览器打开后的效果:


(三)使用mermaid插件

由于mermaid的日益普及,已经存在许多包含mermaid渲染器的插件,比如编辑器插件就支持:Visual Studio Code、Sublime Text 3、Vim、Atom、Typora等。

本文就是此类应用场景,依托Typora上的mermaid插件实现代码绘制饼图。


3. Typora绘制饼图简介


Typora 集成了Markdown绘图扩展,支持通过mermaid插件来实现代码绘制饼图(Pie Chart)。

Typora代码绘制饼图的实现原理如下:

(1)用mermaid代码(符合饼图的DSL)来描述想要绘制的饼图;

(2)调用mermaid插件(解析、渲染器)对mermaid代码进行解析并渲染后动态生成和显示相应饼图。

注:当 Typora 将 Markdown 文档导出为 HTML、PDF、epub、docx 文件格式时,相关渲染图也将包括在内;但是当 Typora 将Markdown 导出为当前版本的其他文件格式时,相关渲染图将不包括在内。


下面就进一步来对Typora利用mermaid插件实现代码绘制饼图进行详细介绍。



4. Typora绘制饼图语法及说明


因目前mermaid对饼图的支持还比较简单,故Typora利用mermaid代码绘制饼图非常简单。

语法描述如下:

语法说明如下:

1、饼图首先以 pie关键字开始(第2行)

2、紧随其后的是title关键字及饼图标题文本(第2行)。注:该部分是可选的

3、接下来是数据集DataSet(第3-5行):

(1)"[dataKey]"——饼图中用双引号括起来的部分是饼图数据标签

(2):——分号作为分隔符

(3)[dataValue]——必须是正数值(最多支持两位小数)



5. 样例


5.1 简单样例


样例代码如下:

mermaid渲染后的饼图效果如下:


5.2 简单样例(带正小数)


样例代码如下:

mermaid渲染后的饼图效果如下:


结束语


通过上面内容的详细介绍,相信感兴趣的朋友们已经对Typora通过mermaid插件实现代码绘制饼图有了一个比较深入的了解。

接下来我会继续针对Typora代码绘制其他特定类型的图进行详细介绍,敬请大家关注后续文章!

本文为原创,如果文章对您有所帮助,喜欢的话就点个赞加关注支持一下哈:)



参考资料


撰写本文参考了如下资料: