《利用python进行数据分析》一书的第8章,关于matplotlib库的使用,各小节的代码。

# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time # 1、matplotlib API入门
# 1.1、Figure和Subplot
# 创建figure对象
fig = plt.figure(1) # 创建一个figure窗口,配合plt.show弹出
# 创建subplot
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
# 创建subplot之后使用绘图命令(如plt.plot),将在最近用过的子图上进行创建
sp3 = plt.plot(np.random.randint(-10, 20, 50).cumsum(), 'k--') # 连线图,k黑色,--虚线
# 调用之前创建的subplot对象可以直接在上面画图
np.random.seed(10)
sp2 = ax2.hist(np.random.randn(10000), bins=100, color='b', alpha=0.5) # 统计直方图(柱状图),显示原数组中各(段)元素的个数
# 各参数依次为 以正态分布随机产生10000个样本 分成100段 蓝色 透明度0.5(1完全不透明0完全透明)
sp1 = ax1.scatter(np.arange(30), np.random.random(30)) # 散点图,依次给定横纵坐标
# plt.show()
# plt.figure方法和add_subplot方法可一步到位:plt.subplots
fig, axes = plt.subplots(1, 2)
sp4 = axes[0].plot(np.random.random(10), 'y*-') # 和matlab一样的习惯
sp5 = axes[1].bar(np.arange(5), np.random.randint(1, 10, 5), color='r')
# plt.show()
# 像matlab做的图周边有一大圈白边,plt可以自定义修改白边大小。(也可以在弹出来的图中进行交互式修改)
fig, axes = plt.subplots(2, 2)
axes[0, 0].scatter(np.arange(30), np.random.random(30))
axes[0, 1].hist(np.random.randn(10000), bins=100, color='b', alpha=0.5)
axes[1, 0].plot(np.random.randint(-10, 20, 50).cumsum(), 'k--')
plt.subplots_adjust(hspace=0, wspace=0) # 高度留白、宽度留白均设为0。也可以用bottom、top、left、right替代
# plt.show()
print('1.1······························↑')
# 1.2、颜色、标记与线型
# plot(线型图)指定线的颜色(color关键字)、标记(marker关键字)、线型(linestyle关键字)
fig = plt.figure(4)
data = np.random.randn(10)
# matlab式表达(颜色需要放在标记与线型前面)
# plt.plot(data,'b*--')
# 关键字式表达,其中颜色可用RGB格式(如#CECE00)
plt.plot(data, color='r', marker='*', linestyle='--') # 缺省线性插值
plt.plot(data, 'b*--', drawstyle='steps-post') # 阶跃,不插值
# plt.show()
print('1.2······························↑')
# 1.3、刻度、标签与图例
# 先画一个图
fig = plt.figure(5)
ax = fig.add_subplot(111)
data = np.random.randint(-20, 23, 1000)
plt.plot(data.cumsum(),linewidth=1)
# 坐标轴刻度
ticks = ax.set_xticks(range(0, 1001, 100))
# 坐标轴刻度标签
label = ['0.' + str(i) + 'k' for i in range(10)]
label.append('1k')
labels = ax.set_xticklabels(label, rotation=30, fontsize=10)
# 设置轴标签
xlabel = ax.set_xlabel(r'$X_{axis}$')
# y轴相应操作
ax.set_yticks(range(-200,801,100))
ax.set_yticklabels([str(i) for i in range(-200,801,100)])
ax.set_ylabel('$Y_{axis}$',rotation=60)
# 图标题
ax.set_title('demonstrate')
# 再加一条曲线
data2 = np.random.random(1000)
plt.plot(data2.cumsum(),linewidth=1)
# 添加图例
ax.legend(['one','two'],loc='best')
print('1.3······························↑')
# 1.4、注解以及在Subplot上绘图
# 注解可通过text、arrow和annotate进行添加
# 三种注解方法,text文字;arrow箭头;annotate文字+箭头。
ax.text(100,500,'Hello plt!',family='monospace',fontsize=10) # 依次给定横纵坐标、文本、字体、字号
ax.arrow(300,300,200,200) # (300,300)指向(500,500)的线段,起点 + 位移
ax.annotate('this',xy=(900,700),xytext=(600,600),arrowprops=dict(color='blue',connectionstyle='arc3,rad=1.5',arrowstyle='->'))
# 在图表中绘图(加图形)
# 首先创建块对象shp
rect=plt.Rectangle((0,100),1000,100,color='blue',alpha=0.05)
# 再通过add_patch方法加到坐标轴中
ax.add_patch(rect)
print('1.4······························↑')
# 1.5、将图表保存到文件
# 保存前额外补充一个功能,给两条曲线之间的区域上色(或打阴影)
x=np.arange(0,1000,1)
cum1 = data.cumsum()
cum2 = data2.cumsum()
ax.fill_between(x, cum1, cum2, where=cum2 >= cum1, facecolor='blue', interpolate=True,alpha=0.365)
ax.fill_between(x, cum1, cum2, where=cum2 <= cum1, facecolor='red', interpolate=True,alpha=0.565,hatch='/')
fig.savefig('withBlank.png',dpi=200) # 保存格式由文件后缀名给定,dpi(每英寸点数)指定200,缺省100
fig.savefig('withoutBlank.svg',dpi=500,bbox_inches='tight') # 保存为svg格式,dpi300,去掉周围的白边框
print('1.5······························↑')
# matplotlib中的图表可通过.rc()方法进行图像大小、边距、配色、字体等全局参数的修改,这些参数大部分已经在上边创建图表时进行了相应的设置。
# plt.show() # 2、pandas中的绘图函数
# pandas中的Series、DataFrame等对象自带由行标签、列标签、数据等信息,pandas自带的绘图函数会自动利用这些信息
fig,axes = plt.subplots(2,2) # figure(6)
# 2.1、线型图
np.random.seed(233)
# Series,以index为横坐标,以value为一条曲线
sr = pd.Series(np.random.randn(10).cumsum(),index=range(0,100,10))
sr.plot(color='red',marker='o',linestyle='--',ax=axes[0,0]) # 直接plot一个Series会同时利用其value数据(曲线)和index数据(横坐标,前提index为数字,可排序的那种)
plt.grid(True,linestyle='--',linewidth=1,color='grey',alpha=0.2)
# plt.show()
# DataFrame,以index为横坐标,以value为多条曲线,以columns为各曲线的标签
df = pd.DataFrame(np.random.randn(10,5).cumsum(axis=0))
df.plot(ax=axes[0,1]) # 关键字subplots为True时各条曲线画在不同子图中,反之画在一张图中
# plt.show()
# 2.2、柱状图
# 在plot方法中指定关键字kind为bar或barh即可,bar的时候series的index无限制,可为字符串等
sr.plot(kind='bar',ax=axes[1,0])
df.plot(kind='barh',ax=axes[1,1])
fig,axes = plt.subplots(2,2) # 再新建一张图,figure(8)
df.plot(kind='barh',ax=axes[0,0],stacked=True) # 生成堆积柱状图(尽管这个例子不适合堆积柱状图……)
# plt.show()
# 2.3、直方图与密度图
# 直方图对应hist方法
sr = pd.concat([pd.Series(np.random.randn(1000)), pd.Series(np.random.normal(5,2.5,size=1000))])
# print(sr.value_counts())
# print(sr.describe())
sr.hist(bins=100,ax=axes[0,1],density=True,alpha=0.68,color='grey') # normed关键字用于指定进行归一化
# 密度图对应plot方法中的kind='kde'
sr.plot(kind='kde',ax=axes[0,1],style='b--')
# 2.4、散布图
# 散点图在matplotlib中用scatter方法实现
# pandas中的series对象无scatter类型plot方法
# pandas中的dataframe对象可使用scatter类型的plot方法,需要指定两列数据对应x、y轴数据
sr = pd.concat([pd.Series(np.random.randn(1000)), pd.Series(np.random.normal(5,2.5,size=1000))])
df = pd.DataFrame(np.random.randn(100,6).cumsum(axis=0))
df.plot(kind='scatter',x=1,y=5,ax=axes[1,0])
# print(df)
# 更多时候画散点图还是需要通过plt.scatter来实现
plt.scatter(df.ix[:,1],df.ix[:,2],axes=axes[1,1])
plt.show()

《python for data analysis》第八章,绘图与可视化的更多相关文章

  1. 《python for data analysis》第十章,时间序列

    < python for data analysis >一书的第十章例程, 主要介绍时间序列(time series)数据的处理.label:1. datetime object.time ...

  2. 数据分析---《Python for Data Analysis》学习笔记【04】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  3. 数据分析---《Python for Data Analysis》学习笔记【03】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  4. 数据分析---《Python for Data Analysis》学习笔记【02】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  5. 数据分析---《Python for Data Analysis》学习笔记【01】

    <Python for Data Analysis>一书由Wes Mckinney所著,中文译名是<利用Python进行数据分析>.这里记录一下学习过程,其中有些方法和书中不同 ...

  6. 《python for data analysis》第九章,数据聚合与分组运算

    # -*- coding:utf-8 -*-# <python for data analysis>第九章# 数据聚合与分组运算import pandas as pdimport nump ...

  7. 《python for data analysis》第七章,数据规整化

    <利用Python进行数据分析>第七章的代码. # -*- coding:utf-8 -*-# <python for data analysis>第七章, 数据规整化 imp ...

  8. 《python for data analysis》第五章,pandas的基本使用

    <利用python进行数据分析>一书的第五章源码与读书笔记 直接上代码 # -*- coding:utf-8 -*-# <python for data analysis>第五 ...

  9. 《python for data analysis》第四章,numpy的基本使用

    <利用python进行数据分析>第四章的程序,介绍了numpy的基本使用方法.(第三章为Ipython的基本使用) 科学计算.常用函数.数组处理.线性代数运算.随机模块…… # -*- c ...

  10. 学习笔记之Python for Data Analysis

    Python for Data Analysis, 2nd Edition https://www.safaribooksonline.com/library/view/python-for-data ...

随机推荐

  1. mybatis源码解析之Configuration加载(二)

    概述 上一篇我们讲了configuation.xml中几个标签的解析,例如<properties>,<typeAlises>,<settings>等,今天我们来介绍 ...

  2. [SCOI2005]扫雷

    我们可以发现...最开始的两个...只有两种情况...直接枚举一下...递推出结果好了... 呆码: #include<iostream> #include<cstring> ...

  3. 杭电ACM1007

    Quoit Design Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tot ...

  4. Python机器学习(基础篇---监督学习(线性分类器))

    监督学习经典模型 机器学习中的监督学习模型的任务重点在于,根据已有的经验知识对未知样本的目标/标记进行预测.根据目标预测变量的类型不同,我们把监督学习任务大体分为分类学习与回归预测两类.监督学习任务的 ...

  5. jmeter之关联

    前言:当请求之间有依赖关系,比如一个请求的入参是另一个请求返回的数据,这时候就需要用到关联处理,Jmeter可以通过“后置处理器”中的“正则表达式提取器”来处理关联. 一.后置处理器-------正则 ...

  6. 数据库between and

    在此记录一下,between相当于大于等于,and相当于小于,举个例子:select * from A where modefytime between '31-3月 -16' and '1-4月 - ...

  7. 编辑器测试-TinyMCE

    一级标签 二级便签 引用段落1231456456 普通段落 链接 简书 https://www.jianshu.com/p/edee77363855 import pygame WINWIDTH = ...

  8. 今日bug:error: invalid array assignment

    错误代码: struct STUD { int ID;//学号 ]; float score; }stud; STUD SS[]; student.open("student.dat&quo ...

  9. MongoDB的安装和使用

    Step1:下载和安装 下载地址:http://dl.mongodb.org/dl/win32/x86_64 安装:一直按照默认指示去安装或者选择自己喜欢的路径安装. Step2:配置环境变量 安装完 ...

  10. H5中用postMessage传递数据,解决localStorage不能跨域问题

    localStorage不能跨域,所以在A域名下用localStorage.YourKey方式存储的值,在B域名下是不能取到的. 所以需要转变思路,目前主要使用的两种方式: 一种方式:在A.B两个页面 ...