是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
源: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 等)。
但是它的強大之處,應該是在于結合前端的知識,繪制更多動態效果的圖形,讓圖形的可視化效果更美觀
CSS實現餅圖效果。
沒什么卵用,但有趣的知識增加了。hello小伙伴們好,我是柴老師。今天我們來繼續分享一個好玩的案例。
它有這樣的需求,要求我們用純CS5的方式實現餅圖。這個餅圖一共是到4個顏色,每個色值占1/4。
大家想想看,如果不讓你用其他的就用純CS5如何來做?我們直接過來一起來實現一下。其實實現這個功能它的思路也比較容易。我們來一起看一下。
我們可以通過一個Div給它創建出來,無非添加一個圓角為50%。這個圓大家想想看它一共是,然后可以給這個盒子創建四個背景,每一個占90度是不是就實現這個小需求了。
這里提供了四個色值,分別是紅色、綠色、黃色以及紫色。這樣我們的紅色它站的角度是0到90度對不對?
綠色它占的角度是90度,然后到270度。再往下我們的黃色它占的是180度,最后這個紫色它是270度,到我們的360度是不是這樣個邏輯?邏輯有了以后具體用哪個技術來實現?其實我們要用到一個CS5,它叫做conic gradient,這個函數可以幫助我們去創建不同的四個背景以及它相關的一個角度。
接下來我們先過來創建個圓出來。這里我創建了一個div,然后上面它的寬高都是,如何讓它變成一個圓?是不是加上一個圓角就可以了?我們加個圓角為50%,這樣它就會出現一個圓對不對?
我們保存一下,先過來看一下我們的圓,大家看它變成了一個圓,然后接著用我們的關鍵去創建它的一個四個背景。我們先過來給它來一個background,然后用一下我們這個核心函數,把它放過來,這個函數是不是需要調用,然后在里面我們依次把這個顏色和它對應的角度給它渲染出來就可以了。
第一個是我們的紅色,紅色它所占的角度是90度,咱們給一個90度。第二個是綠色,它是90度到180度,那我們就先寫一個90,然后再來一個green到180。
第二個green也創建好了,再往后是我們的yellow,是180-270,好yellow 180,再來一個yellow,它是270結束。最后一個是我們的紫色,我們的purple,purple它一直到最后就可以了,從270開始,咱們就寫一個270,前面這個別忘了加單位,都給它把單位加上。
大家看一下這個完整代碼。第一個顏色值第二個顏色值,咱們初始和咱們的結尾都不需要寫這個區間。這樣寫完以后我們可以過來預覽一下,是不是已經變成了我們想要這個樣子。
咱們保存一下過來看,大家看這個擁有4個色值的餅圖是不是就已經實現了。后續大家可以利用這個函數實現簡單的餅圖,大家可以在這個函數里邊隨意調整我們的顏色以及它所占的角度。
今天的分享就先到這里,沒有什么卵用,但是有趣的東西又增加了!好玩
*請認真填寫需求信息,我們會在24小時內與您取得聯系。