Asprin

导航

《python for data analysis》第八章,绘图与可视化

《利用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()

posted on 2018-07-23 20:23  Asprin  阅读(379)  评论(0)    收藏  举报