python 画图--饼图

python 画图--饼图

这是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 ( xexplode=Nonelabels=Nonecolors=Noneautopct=Nonepctdistance=0.6shadow=Falselabeldistance=1.1startangle=None, radius=Nonecounterclock=Truewedgeprops=Nonetextprops=Nonecenter=(00)frame=Falsehold=Nonedata=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 (patchestexts):

If autopct is not None, return the tuple (patchestextsautotexts), 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



  • 36
    点赞
  • 99
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值