Python数据分析基础——图与图表——matplotlib

参考文献:《Python数据分析基础》

前言

Python提供了若干种用于绘图的扩展包,包括matplotlib、pandas、ggplot和seaborn。因为matplotlib是最基础的扩展包,它为pandas和seaborn提供了一些基础的绘图概念和语法。

matplotlib

matplotlib是一个绘图库,创建的图形可达到出版的质量要求。matplotlib提供了对图形各个部分进行定制的功能。

条形图

条形图表示一组分类数值。

创建脚本
#!/usr/bin/env python3
import matplotlib.pyplot as plt
plt.style.use('ggplot')

customers = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']
customers_index = range(len(customers))
sale_amounts = [127, 90, 201, 111, 232]

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.bar(customers_index, sale_amounts, align='center', color='darkblue')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
plt.xticks(customers_index, customers, rotation=0, fontsize='small')

plt.xlabel('Customer Name')
plt.ylabel('Sale Amount')
plt.title('Sale Amount per Customer')

plt.savefig('bar_plot.png', dpi=400, bbox_inches='tight')
plt.show()
脚本代码注释
import matplotlib.pyplot as plt
plt.style.use('ggplot')

这部分中,第一行代码调用了pyplot函数,该函数是有命令风格的函数的集合。第二行代码使用ggplot样式表来模拟ggplot2风格的图形。

customers = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO']
customers_index = range(len(customers))
sale_amounts = [127, 90, 201, 111, 232]

这部分代码创建了条形图的准备数据。其中customers_index为range函数创建的一个可迭代对象,其本质是customers中每个元素的索引值,因为xticks函数需要引用索引位置和标签值。

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

这部分代码是在创建一个基础图(也可以称之为画布)和子图。figure函数的功能是创建一个基础图。add_subplot函数用于创建子图,该函数存在三个参数,表示为把基础图分割成几行几列,并将图像画在第几块上。例如,在这个脚本中,表示将基础图分割成一行一列,并使用这个唯一的子图。

ax1.bar(customers_index, sale_amounts, align='center', color='darkblue')

bar函数函数的功能是绘制柱状图,其参数为柱状图的基本性质。在该例中,customers_index为柱状图的位置序列;sale_amounts为柱状图的数值序列,也就是y轴的值;align设置了柱状图的对齐方式,有center和edge两个参数可以选择,若无参数,默认为center;color设置了柱状图的颜色。

ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

xaxis和yaxis函数是分别对x轴和y轴操作的函数,set_ticks_position函数用于设置刻度线位置。

plt.xticks(customers_index, customers, rotation=0, fontsize='small')

xticks函数用于坐标变名,换句话说,是将之前默认的坐标模式更改为自己想要的样式。在本例中,第一个参数为坐标序列值,第二个参数为新的坐标名称,第三个参数代表坐标轴的旋转角度,第四个参数是坐标字体的大小。

plt.xlabel('Customer Name')
plt.ylabel('Sale Amount')
plt.title('Sale Amount per Customer')

这部分代码,设定了图表名称和坐标轴名称。

plt.savefig('bar_plot.png', dpi=400, bbox_inches='tight')
plt.show()

这部分代码,首先是将统计图保存在当前文件夹内,dpi设置了图形分辨率,bbox_inches='tight’代表将图形四周的空白部分去掉。show函数指示matplotlib在一个新的窗口显示统计图。

运行结果——条形图

在这里插入图片描述

直方图

直方图用来表示数值分布。

创建脚本
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')

mu1, mu2, sigma = 100, 130, 15
x1 = mu1 + sigma*np.random.randn(10000)
x2 = mu2 + sigma*np.random.randn(10000)

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
n, bins, patches = ax1.hist(x1, bins=50, density=False, color='darkgreen')
n, bins, patches = ax1.hist(x2, bins=50, density=False, color='orange', alpha=0.5)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

plt.xlabel('Bins')
plt.ylabel('Number of Values in Bin')
fig.suptitle('Histograms', fontsize=14, fontweight='bold')
ax1.set_title('Two Frequency Distributions')

plt.savefig('histogram.png', dpi=400, bbox_inches='tight')
plt.show()
脚本代码注释
mu1, mu2, sigma = 100, 130, 15
x1 = mu1 + sigma*np.random.randn(10000)
x2 = mu2 + sigma*np.random.randn(10000)

这部分代码使用了随机数生成器,创建了两个正态分布变量x1和x2。

n, bins, patches = ax1.hist(x1, bins=50, density=False, color='darkgreen')
n, bins, patches = ax1.hist(x2, bins=50, density=False, color='orange', alpha=0.5)

这部分代码为两个变量创建两个柱形图。hist函数暂且可以认为是生成直方图的函数,它的作用原理类似于循环录入,它会为每一个区间添加数据。简单介绍一下本例中的参数:
变量值
n:直方图向量
bins:返回各个bin的区间范围
patches:返回每个bin里面包含的数据
参数
bins:直方图柱数
density:判断直方图向量是否归一化
color:直方图颜色
alpha:透明度

fig.suptitle('Histograms', fontsize=14, fontweight='bold')
ax1.set_title('Two Frequency Distributions')

suptitle函数用于添加主图标题,set_title函数用于添加子图标题。

运行结果——直方图

在这里插入图片描述

折线图

折线图中的数值点在一条折线上。

创建脚本
#!/usr/bin/env python3
from numpy.random import randn
import matplotlib.pyplot as plt
plt.style.use('ggplot')

plot_data1 = randn(50).cumsum()
plot_data2 = randn(50).cumsum()
plot_data3 = randn(50).cumsum()
plot_data4 = randn(50).cumsum()

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(plot_data1, marker=r'o', color=u'blue', linestyle='-', label='Blue Solid')
ax1.plot(plot_data2, marker=r'+', color=u'red', linestyle='--', label='Red Dashed')
ax1.plot(plot_data3, marker=r'*', color=u'green', linestyle='-.', label='Green Dash Dot')
ax1.plot(plot_data4, marker=r's', color=u'orange', linestyle=':', label='Orange Dotted')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

ax1.set_title('Line Plots: Markers, Colors, and Linestyles')
plt.xlabel('Draw')
plt.ylabel('Random Number')
plt.legend(loc='best')

plt.savefig('line_plot.png', dpi=400, bbox_inches='tight')
plt.show()
脚本代码注释
plot_data1 = randn(50).cumsum()
plot_data2 = randn(50).cumsum()
plot_data3 = randn(50).cumsum()
plot_data4 = randn(50).cumsum()

这部分代码使用randn函数创建随机数据。

ax1.plot(plot_data1, marker=r'o', color=u'blue', linestyle='-', label='Blue Solid')
ax1.plot(plot_data2, marker=r'+', color=u'red', linestyle='--', label='Red Dashed')
ax1.plot(plot_data3, marker=r'*', color=u'green', linestyle='-.', label='Green Dash Dot')
ax1.plot(plot_data4, marker=r's', color=u'orange', linestyle=':', label='Orange Dotted')

这部分代码创建了4条折线。marker参数设定散点的形状,color参数设定了折线颜色,linestyle参数设定了连线样式,label参数保证折线在图例中可以正确标记。

plt.legend(loc='best')

loc='best’会将图例放在最合适的位置。

运行结果——折线图

在这里插入图片描述

散点图

散点图表示两个数值变量之间的相对关系,这两个变量分别位于两个数轴上。散点图有助于识别出变量之间是否具有正相关或负相关。

创建脚本
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')

x = np.arange(start=1., stop=15., step=1.)
y_linear = x + 5. * np.random.randn(14)
y_quadratic = x**2 + 10. * np.random.randn(14)

fn_linear = np.poly1d(np.polyfit(x, y_linear, deg=1))
fn_quadratic = np.poly1d(np.polyfit(x, y_quadratic, deg=2))

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(x, y_linear, 'bo', x, y_quadratic, 'go', x, fn_linear(x), 'b-', x,fn_quadratic(x), 'g-', linewidth=2.)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')

ax1.set_title('Scatter Plots with Best Fit Lines')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.xlim((min(x)-1., max(x)+1.))
plt.ylim((min(y_quadratic)-10., max(y_quadratic)+10.))

plt.savefig('scatter_plot.png', dpi=400, bbox_inches='tight')
plt.show()
脚本代码注释
y_linear = x + 5. * np.random.randn(14.)
y_quadratic = x**2 + 10. * np.random.randn(14.)

通过随机数使数据与一条直线和一条二次曲线稍稍偏离。

fn_linear = np.poly1d(np.polyfit(x, y_linear, deg=1))
fn_quadratic = np.poly1d(np.polyfit(x, y_quadratic, deg=2))

运用numpy,poly1d函数和polyfit函数生成一个线性方程和二次方程。polyfit函数可以计算出某个阶数的多项式拟合模型的系数。poly1d函数可以使用这些系数创建实际的多项式方程。

ax1.plot(x, y_linear, 'bo', x, y_quadratic, 'go', x, fn_linear(x), 'b-', x,fn_quadratic(x), 'g-', linewidth=2.)

这部分代码设置了点和线的性质。

plt.xlim((min(x)-1., max(x)+1.))
plt.ylim((min(y_quadratic)-10., max(y_quadratic)+10.))

这部分代码设置了x轴和y轴的范围。

运行结果——散点图

在这里插入图片描述

箱线图

箱线图可以表示出数据的最小值、第一四分位数、中位数、第三四分位数和最大值。

创建脚本
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')

N = 500
normal = np.random.normal(loc=0.0, scale=1.0, size=N)
lognormal = np.random.lognormal(mean=0.0, sigma=1.0, size=N)
index_value = np.random.random_integers(low=0, high=N-1, size=N)
normal_sample = normal[index_value]
lognormal_sample = lognormal[index_value]
box_plot_data = [normal,normal_sample,lognormal,lognormal_sample]

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

box_labels = ['normal','normal_sample','lognormal','lognormal_sample']
ax1.boxplot(box_plot_data, notch=False, sym='.', vert=True, whis=1.5, showmeans=True, labels=box_labels)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_title('Box Plots: Resampling of Two Distributions')
ax1.set_xlabel('Distribution')
ax1.set_ylabel('Value')

plt.savefig('box_plot.png', dpi=400, bbox_inches='tight')
plt.show()
脚本代码注释
normal = np.random.normal(loc=0.0, scale=1.0, size=N)
lognormal = np.random.lognormal(mean=0.0, sigma=1.0, size=N)
index_value = np.random.random_integers(low=0, high=N-1, size=N)
normal_sample = normal[index_value]
lognormal_sample = lognormal[index_value]
box_plot_data = [normal,normal_sample,lognormal,lognormal_sample]

这部分代码创建了箱线图所需要的数据。

box_labels = ['normal','normal_sample','lognormal','lognormal_sample']

创建了列表,保存了所需的标签。

ax1.boxplot(box_plot_data, notch=False, sym='.', vert=True, whis=1.5, showmeans=True, labels=box_labels)

这一行代码创建了四个箱线图。notch表示箱体是矩形,而不是在中间收缩。sym参数设置了离群点的形状。vert参数设置了箱体的方向,在这里表示箱体是垂直的。whis设置了直线从第一四分位数和第三四分位数延伸出的范围。showmeans表示箱体在显示中位数的同时也显示均值。label参数用来标记箱线图。

运行结果——箱线图

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值