可视化利器-matplotlib

matplotlb是一个可视化绘图库,其强大,接口多,可以直观了解数据
尽量使用numpy.array绘制,图像基本构成:
Data: 数据区,包括数据点、描绘形状
Axis: 坐标轴,包括 X 轴、 Y 轴及其标签、刻度尺及其标签
Title: 标题,数据图的描述
Legend: 图例,区分图中包含的多种曲线或不同分类的数据
其他的还有图形文本 (Text)、注解 (Annotate)等其他描述

常用图形:
曲线图:matplotlib.pyplot.plot(data)
灰度/直方图:matplotlib.pyplot.hist(data)
散点图:matplotlib.pyplot.scatter(data)
箱式/箱线图:matplotlib.pyplot.boxplot(data)


下面以常规图为例,详细记录作图流程及技巧。按照绘图结构,可将数据图的绘制分为如下几个步骤:
导入 matplotlib 包相关工具包
准备数据,numpy 数组存储
绘制原始曲线
配置标题、坐标轴、刻度、图例
添加文字说明、注解
显示、保存绘图结果

color参数:
r 红色
g 绿色
b 蓝色
c cyan
m 紫色
y 土黄色
k 黑色
w 白色



linestyle 参数主要包含虚线、点化虚线、粗虚线、实线,如下:

设置图像尺寸:
plt.rcParams["figure.figsize"] = (12,8)

绘图案例:
ax1=plt.subplot(2,2,1)#子图1
ax2=plt.subplot(2,2,2)#子图2
# 轴取值范围
ax1.set_xlim(x.min()*1.1, x.max()*1.1)
ax1.set_ylim(-1.5,1.5)

# 设置 x, y 轴的刻度值
ax1.set_xticks([2, 4, 6, 8, 10], [r'TWO', r'4', r'6', r'8', r'10'])
ax1.set_yticks([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0],
    [r'-1.0', r'0.0', r'1.0', r'2.0', r'3.0', r'4.0'])

ax1.spines['right'].set_color('none') # 去掉右边的边框线
ax1.spines['top'].set_color('none')  
ax1.xaxis.set_ticks_position('bottom') #移动坐标轴x
ax1.spines['bottom'].set_position(('data', 0))
# 移动左边边框线,相当于移动 y 轴
ax1.yaxis.set_ticks_position('left')
ax1.spines['left'].set_position(('data', 0)) #移动坐标轴y
ax1.plot(x,y1,color='b')# 绘制图1
ax1.set_title(r'$y = \sin(x)$')# 子图1 title
ax2.plot(x,y3)
ax2.set_title(r'$y = \sqrt{x}$')
ax1.text(8,-0.75,r'$x \in R$')
ax1.text(8,-1,r'$y \in R$') #\in 转义为 ∈
# 绘制散点,作为标注
ax1.scatter(2,np.sin(2),50, color ='m')
t = '(2,'+str(round(np.sin(2),2))+')' # 标注文本内容
ax1.annotate(t,xy=(2,np.sin(2)),xytext=(4, 0.75), fontsize=10, color='#090909',arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=0.1', color='#090909'))
ax1.grid(True) #网格

output:


注意:
总图函数一般直接调用,如plt.title,子图需要加set_xx,如ax1.set_titile.

箱式图科普
箱式图又名箱线图,主要用于观察数据集中点以及观察误差点,箱式图构成:

上边缘(Q3+1.5IQR)、下边缘(Q1-1.5IQR)、IQR=Q3-Q1
上四分位数(Q3)、下四分位数(Q1)
中位数
异常值
处理异常值时与3 σ 标准的异同:统计边界是否受异常值影响、容忍度的大小



各常用图形绘图代码

图形选择:
关联分析、数值比较:散点图、曲线图
分布分析:灰度图、密度图
涉及分类的分析:柱状图、箱式图

各类图形绘图代码封装:
散点图
from matplotlib import font_manager
fontP = font_manager.FontProperties()
fontP.set_family('SimHei')
fontP.set_size(14)

# 包装一个散点图的函数便于复用
def scatterplot(x_data, y_data, x_label, y_label, title):

    # 创建一个绘图对象
    fig, ax = plt.subplots()

    # 设置数据、点的大小、点的颜色和透明度
    ax.scatter(x_data, y_data, s = 10, color = '#539caf', alpha = 0.75) #http://www.114la.com/other/rgb.htm

    # 添加标题和坐标说明
    ax.set_title(title)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)
曲线图
# 包装曲线绘制函数
def lineplot(x_data, y_data, x_label, y_label, title):
    # 创建绘图对象
    _, ax = plt.subplots()

    # 绘制拟合曲线,lw=linewidth,alpha=transparancy
    ax.plot(x_data, y_data, lw = 2, color = '#539caf', alpha = 1)

    # 添加标题和坐标说明
    ax.set_title(title)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)
带置信区间曲线图
def lineplotCI(x_data, y_data, sorted_x, low_CI, upper_CI, x_label, y_label, title):
    # 创建绘图对象
    _, ax = plt.subplots()

    # 绘制预测曲线
    ax.plot(x_data, y_data, lw = 1, color = '#539caf', alpha = 1, label = 'Fit')
    # 绘制置信区间,顺序填充
    ax.fill_between(sorted_x, low_CI, upper_CI, color = '#539caf', alpha = 0.4, label = '95% CI')
    # 添加标题和坐标说明
    ax.set_title(title)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)

    # 显示图例,配合label参数,loc=“best”自适应方式
    ax.legend(loc = 'best')

双坐标曲线图
# 双纵坐标绘图函数
def lineplot2y(x_data, x_label, y1_data, y1_color, y1_label, y2_data, y2_color, y2_label, title):
    _, ax1 = plt.subplots()
    ax1.plot(x_data, y1_data, color = y1_color)
    # 添加标题和坐标说明
    ax1.set_ylabel(y1_label, color = y1_color)
    ax1.set_xlabel(x_label)
    ax1.set_title(title)

    ax2 = ax1.twinx() # 两个绘图对象共享横坐标轴
    ax2.plot(x_data, y2_data, color = y2_color)
    ax2.set_ylabel(y2_label, color = y2_color)
    # 右侧坐标轴可见
    ax2.spines['right'].set_visible(True)

ax1 = plt.subplot()
ax1.plot(x,np.sin(x))
ax2=ax1.twinx()
ax2.plot(x,np.cos(x))


灰度图
# 绘制灰度图的函数
def histogram(data, x_label, y_label, title):
    _, ax = plt.subplots()
    res = ax.hist(data, color = '#539caf', bins=10) # 设置bin的数量
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
    return res
堆叠直方图
# 绘制堆叠的直方图
def overlaid_histogram(data1, data1_name, data1_color, data2, data2_name, data2_color, x_label, y_label, title):
    # 归一化数据区间,对齐两个直方图的bins
    max_nbins = 10
    data_range = [min(min(data1), min(data2)), max(max(data1), max(data2))]
    binwidth = (data_range[1] - data_range[0]) / max_nbins
    bins = np.arange(data_range[0], data_range[1] + binwidth, binwidth) # 生成直方图bins区间

    # Create the plot
    _, ax = plt.subplots()
    ax.hist(data1, bins = bins, color = data1_color, alpha = 1, label = data1_name)
    ax.hist(data2, bins = bins, color = data2_color, alpha = 0.75, label = data2_name)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
    ax.legend(loc = 'best')

密度图
# 绘制密度估计曲线
def densityplot(x_data, density_est, x_label, y_label, title):
    _, ax = plt.subplots()
    ax.plot(x_data, density_est(x_data), color = '#539caf', lw = 2)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
柱状图
# 定义绘制柱状图的函数
def barplot(x_data, y_data, error_data, x_label, y_label, title):
    _, ax = plt.subplots()
    # 柱状图
    ax.bar(x_data, y_data, color = '#539caf', align = 'center')
    # 绘制方差
    # ls='none'去掉bar之间的连线
    ax.errorbar(x_data, y_data, yerr = error_data, color = '#297083', ls = 'none', lw = 5)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)

堆积柱状图
# 绘制堆积柱状图
def stackedbarplot(x_data, y_data_list, y_data_names, colors, x_label, y_label, title):
    _, ax = plt.subplots()
    # 循环绘制堆积柱状图
    for i in range(0, len(y_data_list)):
        if i == 0:
            ax.bar(x_data, y_data_list[i], color = colors[i], align = 'center', label = y_data_names[i])
        else:
            # 采用堆积的方式,除了第一个分类,后面的分类都从前一个分类的柱状图接着画
            # 用归一化保证最终累积结果为1
            ax.bar(x_data, y_data_list[i], color = colors[i], bottom = y_data_list[i - 1], align = 'center', label = y_data_names[i])
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
    ax.legend(loc = 'upper right') # 设定图例位置

分组柱状图
# 绘制分组柱状图的函数
def groupedbarplot(x_data, y_data_list, y_data_names, colors, x_label, y_label, title):
    _, ax = plt.subplots()
    # 设置每一组柱状图的宽度
    total_width = 0.8
    # 设置每一个柱状图的宽度
    ind_width = total_width / len(y_data_list)
    # 计算每一个柱状图的中心偏移
    alteration = np.arange(-total_width/2+ind_width/2, total_width/2+ind_width/2, ind_width)

    # 分别绘制每一个柱状图
    for i in range(0, len(y_data_list)):
        # 横向散开绘制
        ax.bar(x_data + alteration[i], y_data_list[i], color = colors[i], label = y_data_names[i], width = ind_width)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
    ax.legend(loc = 'upper right')

箱式图
# 定义绘图函数
def boxplot(x_data, y_data, base_color, median_color, x_label, y_label, title):
    _, ax = plt.subplots()

    # 设置样式
    ax.boxplot(y_data
               # 箱子是否颜色填充
               , patch_artist = True
               # 中位数线颜色
               , medianprops = {'color': base_color}
               # 箱子颜色设置,color:边框颜色,facecolor:填充颜色
               , boxprops = {'color': base_color, 'facecolor': median_color}
               # 猫须颜色whisker
               , whiskerprops = {'color': median_color}
               # 猫须界限颜色whisker cap
               , capprops = {'color': base_color})

    # 箱图与x_data保持一致
    ax.set_xticklabels(x_data)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值