源:Python數據之道
作者:Peter
整理:陽哥
前不久,陽哥在「Python數據之道」分享了讀者投稿的文章,較為綜合的介紹了可視化庫 Highcharts ,這個一個 JavaScript 下的可視化工具,同時也有 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 繪制圖形的主要步驟如下:
最后是個人的一點感覺:利用 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):
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>]:
Additional kwargs: hold=[True|False] overrides default hold state
之前已經發布了三篇Typora代碼繪圖的文章,如下:
1、Typora筆記之繪圖綜述
2、Typora筆記之繪制流程圖詳述(一)
3、Typora筆記之繪制流程圖詳述(二)
本文接著對Typora通過mermaid插件實現代碼繪制餅圖進行詳細介紹,希望能對感興趣的朋友有所幫助。
注:原計劃接下來是應該寫代碼繪制序列圖的,但粗略地過了一下,要寫的內容不少,鑒于之前撰寫第三篇文章耗時過長,于是第四篇文章就先選個比較簡單的代碼繪制餅圖了。
本次分享的內容目錄如下:
前言
餅圖簡介
mermaid簡介
Typora繪制餅圖簡介
Typora繪制餅圖語法及說明
樣例
結束語
參考資料
大家對于餅圖想必已經是非常熟悉了,不過為了文章的完整性,這里再做個簡單回顧。
餅圖(Pie Chart),亦稱餅狀圖,是一個劃分為幾個扇形的圓形統計圖表,用于描述量、頻率或百分比之間的相對關系。在餅圖中,每個扇區的弧長(以及圓心角和面積)大小為其所表示的數量的比例。這些扇區合在一起剛好是一個完全的圓形。顧名思義,這些扇區拼成了一個切開的餅形圖案。 —— 來自維基百科
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插件實現代碼繪制餅圖。
Typora 集成了Markdown繪圖擴展,支持通過mermaid插件來實現代碼繪制餅圖(Pie Chart)。
Typora代碼繪制餅圖的實現原理如下:
(1)用mermaid代碼(符合餅圖的DSL)來描述想要繪制的餅圖;
(2)調用mermaid插件(解析、渲染器)對mermaid代碼進行解析并渲染后動態生成和顯示相應餅圖。
注:當 Typora 將 Markdown 文檔導出為 HTML、PDF、epub、docx 文件格式時,相關渲染圖也將包括在內;但是當 Typora 將Markdown 導出為當前版本的其他文件格式時,相關渲染圖將不包括在內。
下面就進一步來對Typora利用mermaid插件實現代碼繪制餅圖進行詳細介紹。
因目前mermaid對餅圖的支持還比較簡單,故Typora利用mermaid代碼繪制餅圖非常簡單。
語法描述如下:
語法說明如下:
1、餅圖首先以 pie關鍵字開始(第2行)
2、緊隨其后的是title關鍵字及餅圖標題文本(第2行)。注:該部分是可選的。
3、接下來是數據集DataSet(第3-5行):
(1)"[dataKey]"——餅圖中用雙引號括起來的部分是餅圖數據標簽
(2):——分號作為分隔符
(3)[dataValue]——必須是正數值(最多支持兩位小數)
樣例代碼如下:
經mermaid渲染后的餅圖效果如下:
樣例代碼如下:
經mermaid渲染后的餅圖效果如下:
通過上面內容的詳細介紹,相信感興趣的朋友們已經對Typora通過mermaid插件實現代碼繪制餅圖有了一個比較深入的了解。
接下來我會繼續針對Typora代碼繪制其他特定類型的圖進行詳細介紹,敬請大家關注后續文章!
本文為原創,如果文章對您有所幫助,喜歡的話就點個贊加關注支持一下哈:)
撰寫本文參考了如下資料:
*請認真填寫需求信息,我們會在24小時內與您取得聯系。