新西兰服务器

Python中matplotlib如何绘制经典的饼图和条形图


Python中matplotlib如何绘制经典的饼图和条形图

发布时间:2021-12-02 18:00:47 来源:高防服务器网 阅读:55 作者:小新 栏目:开发技术

小编给大家分享一下Python中matplotlib如何绘制经典的饼图和条形图,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

matplotlib是基于numpy的一套Python工具包。这个包提供了丰富的数据绘图工具,主要用于绘制一些统计图形。你可以找到很多各式各样的 例子:

通过数据绘图,我们可以将枯燥的数字转换成容易被人们接受的图表,从而让人留下更加深刻的印象。实际上,早在一百多年前, 南丁格尔就曾经用统计图形来说服英国政府,以改善军队的卫生状况。

我们将以GDP数据为例子,看看如何绘制经典的饼图和条形图。

数据

下面是我们要使用的数据,为2011年GDP前十的国家以及其具体的GDP:

USA        15094025  China      11299967  India       4457784  Japan       4440376  Germany     3099080  Russia      2383402  Brazil      2293954  UK          2260803  France      2217900  Italy       1846950

饼图

我们先来绘制饼图 (pie plot)。饼图适用于表达各个国家GDP所占的百分比。每一小块的面积代表了占比的多少:

具体代码如下,可以看到我们主要使用了matplotlib.pyplot工具包:

# Make a pie chart# This script is written by Vamei, http://www.cnblogs.com/vamei# you may freely use it.import matplotlib.pyplot as plt# quants: GDP# labels: country namelabels   = []  quants   = []# Read datafor line in file('../data/major_country_gdp'):      info = line.split()      labels.append(info[0])      quants.append(float(info[1]))# make a square figureplt.figure(1, figsize=(6,6))# For China, make the piece explode a bitdef explode(label, target='China'):    if label == target: return 0.1    else: return 0  expl = map(explode,labels)# Colors used. Recycle if not enough.colors  = ["pink","coral","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()

条形图

下面我们尝试一下条形图(bar plot)。用每个长条的高度代表每个国家的GDP,长条越高,GDP值越高:

代码如下:

"""Make a pie chart  This script is written by Vamei, http://www.cnblogs.com/vamei  you may freely use it."""import matplotlib.pyplot as pltimport numpy as np# quants: GDP# labels: country namelabels   = []  quants   = []# Read datafor line in file('../data/major_country_gdp'):      info = line.split()      labels.append(info[0])      quants.append(float(info[1]))  width = 0.4ind = np.linspace(0.5,9.5,10)# make a square figurefig = plt.figure(1, figsize=(12,6))  ax  = fig.add_subplot(111)# Bar Plotax.bar(ind-width/2,quants,width,color='coral')# Set the ticks on x-axisax.set_xticks(ind)  ax.set_xticklabels(labels)# labelsax.set_xlabel('Country')  ax.set_ylabel('GDP (Billion US dollar)')# titleax.set_title('Top 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5})  plt.show()

该代码中我们利用了ax对象,以便控制刻度以及刻度所对应的国家名。这与我们在pie plot所做的有些不同(pie plot也可以这样实现,只是没有必要而已)。

以上是“Python中matplotlib如何绘制经典的饼图和条形图”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注高防服务器网行业资讯频道!

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[