Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
源:Python數(shù)據(jù)之道
作者:Peter
整理:陽哥
前不久,陽哥在「Python數(shù)據(jù)之道」分享了讀者投稿的文章,較為綜合的介紹了可視化庫 Highcharts ,這個(gè)一個(gè) JavaScript 下的可視化工具,同時(shí)也有 Python 版本。前文鏈接如下:
不少同學(xué)對(duì)這個(gè)工具感興趣,今天來跟大家介紹下如何用這個(gè)工具來繪制餅圖。大家可以對(duì)照自己常用的 Python 庫,看看哪些工具更適合自己。
本文中介紹的是如何利用 python-highcharts 繪制各種餅圖來滿足不同的需求,主要包含:
首先我們看看整體的效果:
整理的代碼如下:
上面的基礎(chǔ)餅圖在 Highcharts 中默認(rèn)是每個(gè)區(qū)塊的顏色是各不相同的,如果我們想每個(gè)區(qū)塊的顏色是相同的,或者某幾個(gè)區(qū)塊的顏色是相同的,該如何操作呢?
首先看看整體的效果圖:
整體的代碼如下:從導(dǎo)入庫到數(shù)據(jù)的添加設(shè)置、以及參數(shù)項(xiàng)的配置等
其中,重點(diǎn)的參數(shù)設(shè)置看這里:
Highcharts 中就是通過 Highcharts.getOptions().colors 來設(shè)置默認(rèn)的顏色。我們改變下設(shè)置,繪制另一種顏色的餅圖:
如果我們想某幾個(gè)區(qū)塊顯示相同的顏色,可以設(shè)置相同的數(shù)值,首先看看具體的效果圖:
可以看到我們將6個(gè)區(qū)塊的顏色分成了3大類,就是通過上面的方法來實(shí)現(xiàn)的。如果我們?cè)O(shè)置成0-5的數(shù)值,即每個(gè)區(qū)塊的顏色各不相同,那么就是基礎(chǔ)餅圖的樣子:
上面提到的各種餅圖都是沒有圖例的,同時(shí)在區(qū)塊中也沒有直接顯示原始數(shù)據(jù),下面介紹方法來實(shí)現(xiàn)這兩種效果:
圖例和數(shù)據(jù)顯示的代碼設(shè)置:
上面介紹了各種單個(gè)餅圖的制作,下面講解如何利用 python-highcharts 制作雙層餅圖。看看整體的效果:
從上圖中我們可以看到:主要是有5種顏色
數(shù)據(jù)中顯示每個(gè)大類中還有子類,比如:MSIE 父類中還有子類 MSIE6.0、MSIE7.0、MSIE8.0、MSIE9.0?,F(xiàn)在我們看看代碼中數(shù)據(jù)的顯示:
可以很清晰地看到:先顯示父級(jí)的數(shù)據(jù),再顯示子級(jí)的數(shù)據(jù)。整體的代碼如下:
上面介紹的都是如何制作各種餅圖,下面介紹一種制作 扇形圖 的方法。首先看看整體的效果:
上面顯示了5個(gè)類別的數(shù)據(jù),同時(shí)顯示了圖例,并且在扇形圖中顯示了數(shù)據(jù)。整體的代碼如下:
重點(diǎn)的設(shè)置部分:
本文結(jié)合各種實(shí)際案例介紹了如何利用 python-highcharts 來繪制各種不同需求的餅圖或者扇形圖。通過上面案例的介紹,我們發(fā)現(xiàn)使用 Highcharts 繪制圖形的主要步驟如下:
最后是個(gè)人的一點(diǎn)感覺:利用 Highcharts 來進(jìn)行繪圖的確代碼量很大,基本上畫一個(gè)簡(jiǎn)單的餅圖或者柱狀圖都需要大量的代碼(相對(duì)其他自己使用的可視化庫,比如 pyecharts、plotly_express 等)。
但是它的強(qiáng)大之處,應(yīng)該是在于結(jié)合前端的知識(shí),繪制更多動(dòng)態(tài)效果的圖形,讓圖形的可視化效果更美觀
是python畫圖系列第三篇--餅圖
畫餅圖用到的方法為:
matplotlib.pyplot.pie()
參數(shù)為:
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 )
參數(shù)說明:
x (每一塊)的比例,如果sum(x) > 1會(huì)使用sum(x)歸一化
labels (每一塊)餅圖外側(cè)顯示的說明文字
explode (每一塊)離開中心距離
startangle 起始繪制角度,默認(rèn)圖是從x軸正方向逆時(shí)針畫起,如設(shè)定=90則從y軸正方向畫起
shadow 是否陰影
labeldistance label繪制位置,相對(duì)于半徑的比例, 如<1則繪制在餅圖內(nèi)側(cè)
autopct 控制餅圖內(nèi)百分比設(shè)置,可以使用format字符串或者format function
'%1.1f'指小數(shù)點(diǎn)前后位數(shù)(沒有用空格補(bǔ)齊)
pctdistance 類似于labeldistance,指定autopct的位置刻度
radius 控制餅圖半徑
返回值:
如果沒有設(shè)置autopct,返回(patches, texts)
如果設(shè)置autopct,返回(patches, texts, autotexts)
patches -- list --matplotlib.patches.Wedge對(duì)象
texts autotexts -- matplotlib.text.Text對(duì)象
下面是一個(gè)簡(jiǎn)單的示例:
# -*- 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%%') #畫餅圖(數(shù)據(jù),數(shù)據(jù)對(duì)應(yīng)的標(biāo)簽,百分?jǐn)?shù)保留兩位小數(shù)點(diǎn)) plt.title("Pie chart") plt.show() plt.savefig("PieChart.jpg")
下面是結(jié)果:
下面是另一個(gè)示例:
# -*- 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"] #設(shè)置顏色(循環(huán)顯示) # Pie Plot # autopct: format of "percent" string;百分?jǐn)?shù)格式 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
之前已經(jīng)發(fā)布了三篇Typora代碼繪圖的文章,如下:
1、Typora筆記之繪圖綜述
2、Typora筆記之繪制流程圖詳述(一)
3、Typora筆記之繪制流程圖詳述(二)
本文接著對(duì)Typora通過mermaid插件實(shí)現(xiàn)代碼繪制餅圖進(jìn)行詳細(xì)介紹,希望能對(duì)感興趣的朋友有所幫助。
注:原計(jì)劃接下來是應(yīng)該寫代碼繪制序列圖的,但粗略地過了一下,要寫的內(nèi)容不少,鑒于之前撰寫第三篇文章耗時(shí)過長,于是第四篇文章就先選個(gè)比較簡(jiǎn)單的代碼繪制餅圖了。
本次分享的內(nèi)容目錄如下:
前言
餅圖簡(jiǎn)介
mermaid簡(jiǎn)介
Typora繪制餅圖簡(jiǎn)介
Typora繪制餅圖語法及說明
樣例
結(jié)束語
參考資料
大家對(duì)于餅圖想必已經(jīng)是非常熟悉了,不過為了文章的完整性,這里再做個(gè)簡(jiǎn)單回顧。
餅圖(Pie Chart),亦稱餅狀圖,是一個(gè)劃分為幾個(gè)扇形的圓形統(tǒng)計(jì)圖表,用于描述量、頻率或百分比之間的相對(duì)關(guān)系。在餅圖中,每個(gè)扇區(qū)的弧長(以及圓心角和面積)大小為其所表示的數(shù)量的比例。這些扇區(qū)合在一起剛好是一個(gè)完全的圓形。顧名思義,這些扇區(qū)拼成了一個(gè)切開的餅形圖案。 —— 來自維基百科
mermaid是一款免費(fèi)開源的,能在瀏覽器和終端中運(yùn)行的特定類型圖DSL和SVG渲染器,可以通過DSL(圖的文本表示)來繪制簡(jiǎn)單的SVG圖。當(dāng)前版本的mermaid已經(jīng)支持多種特定類型圖,包括:流程圖(Flow Chart)、序列圖(Sequence Diagram)、類圖(Class Diagram))、狀態(tài)圖(State Diagram)、實(shí)體關(guān)系圖(Entity Relationship Diagram)、用戶旅程圖(User Journey Diagram)、甘特圖(Gantt Diagram)、餅圖(Pie Chart)、Git圖(Git Graph)等。
使用mermaid通過代碼繪制圖非常簡(jiǎn)單,原理是將mermaid代碼(Plain Text)通過渲染器(Mermaid JavaScript Library)來轉(zhuǎn)化成圖(Graphs, Gantt Charts, and many other Diagrams)并顯示。
目前使用mermaid實(shí)現(xiàn)代碼繪圖有以下三種方法:
(一)使用mermaid Live Editor:(網(wǎng)址:https://mermaid-js.github.io/mermaid-live-editor/)
如下圖示,在左上側(cè)的Code區(qū)編輯修改mermaid代碼,右側(cè)的Preview區(qū)就會(huì)實(shí)時(shí)顯示出經(jīng)渲染后的圖;在右下側(cè),還能將渲染后的圖直接下載成svg或png格式的圖片等。
(二)用HTML調(diào)用mermaid渲染器
大多數(shù)網(wǎng)絡(luò)瀏覽器(例如Firefox,Chrome和Safari)都可以渲染mermaid,所以可以直接在html文件中添加mermaid代碼,這樣在打開html文件時(shí)瀏覽器就會(huì)直接完成mermaid的渲染工作,顯示出相應(yīng)圖。
示例代碼(MermaidHtmlTest.html):
瀏覽器打開后的效果:
(三)使用mermaid插件
由于mermaid的日益普及,已經(jīng)存在許多包含mermaid渲染器的插件,比如編輯器插件就支持:Visual Studio Code、Sublime Text 3、Vim、Atom、Typora等。
本文就是此類應(yīng)用場(chǎng)景,依托Typora上的mermaid插件實(shí)現(xiàn)代碼繪制餅圖。
Typora 集成了Markdown繪圖擴(kuò)展,支持通過mermaid插件來實(shí)現(xiàn)代碼繪制餅圖(Pie Chart)。
Typora代碼繪制餅圖的實(shí)現(xiàn)原理如下:
(1)用mermaid代碼(符合餅圖的DSL)來描述想要繪制的餅圖;
(2)調(diào)用mermaid插件(解析、渲染器)對(duì)mermaid代碼進(jìn)行解析并渲染后動(dòng)態(tài)生成和顯示相應(yīng)餅圖。
注:當(dāng) Typora 將 Markdown 文檔導(dǎo)出為 HTML、PDF、epub、docx 文件格式時(shí),相關(guān)渲染圖也將包括在內(nèi);但是當(dāng) Typora 將Markdown 導(dǎo)出為當(dāng)前版本的其他文件格式時(shí),相關(guān)渲染圖將不包括在內(nèi)。
下面就進(jìn)一步來對(duì)Typora利用mermaid插件實(shí)現(xiàn)代碼繪制餅圖進(jìn)行詳細(xì)介紹。
因目前mermaid對(duì)餅圖的支持還比較簡(jiǎn)單,故Typora利用mermaid代碼繪制餅圖非常簡(jiǎn)單。
語法描述如下:
語法說明如下:
1、餅圖首先以 pie關(guān)鍵字開始(第2行)
2、緊隨其后的是title關(guān)鍵字及餅圖標(biāo)題文本(第2行)。注:該部分是可選的。
3、接下來是數(shù)據(jù)集DataSet(第3-5行):
(1)"[dataKey]"——餅圖中用雙引號(hào)括起來的部分是餅圖數(shù)據(jù)標(biāo)簽
(2):——分號(hào)作為分隔符
(3)[dataValue]——必須是正數(shù)值(最多支持兩位小數(shù))
樣例代碼如下:
經(jīng)mermaid渲染后的餅圖效果如下:
樣例代碼如下:
經(jīng)mermaid渲染后的餅圖效果如下:
通過上面內(nèi)容的詳細(xì)介紹,相信感興趣的朋友們已經(jīng)對(duì)Typora通過mermaid插件實(shí)現(xiàn)代碼繪制餅圖有了一個(gè)比較深入的了解。
接下來我會(huì)繼續(xù)針對(duì)Typora代碼繪制其他特定類型的圖進(jìn)行詳細(xì)介紹,敬請(qǐng)大家關(guān)注后續(xù)文章!
本文為原創(chuàng),如果文章對(duì)您有所幫助,喜歡的話就點(diǎn)個(gè)贊加關(guān)注支持一下哈:)
撰寫本文參考了如下資料:
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。