畫餅圖

from matplotlib import pyplot as plt 

#調節圖形大小,寬,高
plt.figure(figsize=(6,9))
#定義餅狀圖的標籤,標籤是列表
labels = [u'第一部分',u'第二部分',u'第三部分']
#每一個標籤佔多大,會自動去算百分比
sizes = [60,30,10]
colors = ['red','yellowgreen','lightskyblue']
#將某部分爆炸出來, 使用括號,將第一塊分割出來,數值的大小是分割出來的與其餘兩塊的間隙
explode = (0.05,0,0)

patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors,
                                labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,
                                startangle = 90,pctdistance = 0.6)

#labeldistance,文本的位置離遠點有多遠,1.1指1.1倍半徑的位置
#autopct,圓裏面的文本格式,%3.1f%%表示小數有三位,整數有一位的浮點數
#shadow,餅是否有陰影
#startangle,起始角度,0,表示從0開始逆時針轉,爲第一塊。通常選擇從90度開始比較好看
#pctdistance,百分比的text離圓心的距離
#patches, l_texts, p_texts,爲了獲得餅圖的返回值,p_texts餅圖內部文本的,l_texts餅圖外label的文本

#改變文本的大小
#方法是把每個text遍歷。調用set_size方法設置它的屬性
for t in l_text:
    t.set_size=(30)
for t in p_text:
    t.set_size=(20)
# 設置x,y軸刻度一致,這樣餅圖才能是圓的
plt.axis('equal')
plt.legend()
plt.show()

做者:Kedi
連接:http://www.jianshu.com/p/0a76c94e9db7
來源:簡書
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。

  

 

python 畫圖--餅圖

這是python畫圖系列第三篇--餅圖html

畫餅圖用到的方法爲:python

matplotlib.pyplot.pie()api

 

參數爲:ide

 

[python]  view plain  copy
 
  1. pie(x, explode=None, labels=None,  
  2.     colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'),  
  3.     autopct=None, pctdistance=0.6, shadow=False,  
  4.     labeldistance=1.1, startangle=None, radius=None,  
  5.     counterclock=True, wedgeprops=None, textprops=None,  
  6.     center = (0, 0), frame = False )  


參數說明:this

 

 

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對象spa

texts autotexts -- matplotlib.text.Text對象.net

 

 

下面是一個簡單的示例:scala

 

[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2. import numpy as np    
  3. import matplotlib.mlab as mlab    
  4. import matplotlib.pyplot as plt    
  5. labels=['China','Swiss','USA','UK','Laos','Spain']  
  6. X=[222,42,455,664,454,334]    
  7.   
  8. fig = plt.figure()  
  9. plt.pie(X,labels=labels,autopct='%1.2f%%') #畫餅圖(數據,數據對應的標籤,百分數保留兩位小數點)  
  10. plt.title("Pie chart")  
  11.     
  12.   
  13. plt.show()    
  14. plt.savefig("PieChart.jpg")  


下面是結果:code

 

 

下面是另外一個示例:orm

 

[python]  view plain  copy
 
  1. # -*- coding: utf-8 -*-  
  2. import numpy as np  
  3. import matplotlib.pyplot as plt  
  4. import matplotlib as mpl  
  5.   
  6. def draw_pie(labels,quants):  
  7.     # make a square figure  
  8.     plt.figure(1, figsize=(6,6))  
  9.     # For China, make the piece explode a bit  
  10.     expl = [0,0.1,0,0,0,0,0,0,0,0]   #第二塊即China離開圓心0.1  
  11.     # Colors used. Recycle if not enough.  
  12.     colors  = ["blue","red","coral","green","yellow","orange"]  #設置顏色(循環顯示)  
  13.     # Pie Plot  
  14.     # autopct: format of "percent" string;百分數格式  
  15.     plt.pie(quants, explode=expl, colors=colors, labels=labels, autopct='%1.1f%%',pctdistance=0.8, shadow=True)  
  16.     plt.title('Top 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5})  
  17.     plt.show()  
  18.     plt.savefig("pie.jpg")  
  19.     plt.close()  
  20.   
  21. # quants: GDP  
  22.   
  23. # labels: country name  
  24.   
  25. labels   = ['USA', 'China', 'India', 'Japan', 'Germany', 'Russia', 'Brazil', 'UK', 'France', 'Italy']  
  26.   
  27. quants   = [15094025.0, 11299967.0, 4457784.0, 4440376.0, 3099080.0, 2383402.0, 2293954.0, 2260803.0, 2217900.0, 1846950.0]  
  28.   
  29. 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>]:

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

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

相關文章
相關標籤/搜索