整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

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(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):

  • patches is a sequence of matplotlib.patches.Wedge instances
  • texts is a list of the label matplotlib.text.Text instances.

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

源:Python数据之道

作者:Peter

整理:阳哥

用 Highcharts 绘制饼图,也很强大

前不久,阳哥在「Python数据之道」分享了读者投稿的文章,较为综合的介绍了可视化库 Highcharts ,这个一个 JavaScript 下的可视化工具,同时也有 Python 版本。前文链接如下:

  • 又一个可视化神器Highcharts,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 绘制图形的主要步骤如下:

  1. 导入我们需要的 Highcharts 库,再实例化一个 Highcharts 对象
  2. 数据项的配置:在绘图的时候,数据的配置也很重要。Highcharts中对数据格式要求还是挺高的,而且在数据中还可以对数据进行效果的设置
  3. 图形参数设置:这是整个绘图过程中 最为重要 的部分,主要是包含:图表类型chart(柱状图、饼图、折线图等)、标题title(主标题、副标题)、数据提示工具tooltip、绘图选型plotOptions等配置项的设置
  4. 添加数据项和配置项。在添加配置项的时候,我们可以对最终的图形进行一些效果设置。

最后是个人的一点感觉:利用 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个色值的饼图是不是就已经实现了。后续大家可以利用这个函数实现简单的饼图,大家可以在这个函数里边随意调整我们的颜色以及它所占的角度。

今天的分享就先到这里,没有什么卵用,但是有趣的东西又增加了!好玩