Python常用库之matplotlib

1. 作用:数据可视化

  提供一套表示和操作图形图像对象以及它的内部对象的函数和工具;

2. 三层架构

  Scripting(脚本)层、Artist(表现)层、Backend(后端)层

3. 绘图

3.1 颜色取值

3.2 显示图形取值

3.3 位置取值(图例)

应用实例:

# coding=utf-8
# 0.导入绘图包
import matplotlib .pyplot as plt
import numpy as np
import math
# 1.绘图
# 1.1 颜色
# plt.plot([1,2,3,4],[1,4,9,16],'ro')
# 1.2 x,y范围
# plt.axis([0,5,0,20])
# 1.3 标题
# 解决中文乱码
plt.rcParams['font.sans-serif']=['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号
plt.title(u'平方数据')
# 1.4 传入numpy数据
t = np.arange(0.2,5,0.1)
y1 = list(map(math.sin,math.pi*t))
# 1.5 定义线宽
plt.plot(t,y1,'b-',linewidth=2.0)
# 1.6 添加轴标签
plt.xlabel("自变量x")
plt.ylabel("pi*t的值")
# 1.7 添加图例
plt.legend(['x与pi*t'],loc=2)
# 1.8 添加网格
plt.grid(True)
# 1.9 添加文本(位置坐标,编辑公式,文本框)
plt.text(1.1,0.8,r'$y=x^2$',bbox={'facecolor':'yellow','alpha':0.2})
# 2.显示
plt.show()

划分子图:

# coding=utf-8
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0,5,0.1)
y1 = np.sin(2*np.pi*t)
y2 = np.sin(2*np.pi*t)

# 参数说明:第一个参数:沿着垂直方向分为几部分;第二个参数:沿着水平方向分为几部分;第三个参数:当前的子图号
plt.subplot(211)  # 垂直分为2部分,水平1部分,属于第一个
plt.plot(t,y1,'b-.')
plt.subplot(212)
plt.plot(t,y2,'r-.')
plt.show()

4.日期处理

4.1 未处理

# coding=utf-8
import matplotlib.pyplot as plt
import datetime

events = [datetime.date(2015,1,23),datetime.date(2015,1,28),datetime.date(2015,2,3),datetime.date(2015,2,21),datetime.date(2015,3,15)]

readings = [12,22,25,20,18]
plt.plot(events,readings,'ro')
plt.show()

  4.2 处理后

# coding=utf-8
import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import datetime

# 1.准备数据
events = [datetime.date(2015,1,23),datetime.date(2015,1,28),datetime.date(2015,2,3),datetime.date(2015,2,21),datetime.date(2015,3,15)]
readings = [12,14,15,17,18]

# 2.设置图形基本属性
fig1 = plt.figure(figsize=(8,6))  # 图像比例为:8,6
ax1 = fig1.add_subplot(1,1,1) # 纵横分为几部分,当前的编号
ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m'))  # 设置时间标签显示格式
plt.xticks(events,rotation=45)
plt.title('data1')
plt.plot(events,readings,'o-')
plt.show()

5. 图表类型

  5.1 线性图

data = {'series1':[1,2,3,4,5],
            'series2':[5,6,7,8,9],
            'series3':[6,7,8,9,10]}
    df = pd.DataFrame(data)
    x = np.arange(5)
    plt.axis([0,10,0,12])
    plt.plot(x,df)
    plt.legend(data,loc=1)
    # 参数介绍:显示的内容,结束位置,开始位置,arrowprops设置箭头(颜色,长度,宽度,箭身宽度)
    plt.annotate(r'data_Type',xy=[0,1],xytext=[1,2],arrowprops = dict(facecolor = "r", headlength = 10, headwidth = 3, width = 2))
    plt.show()

  5.2 直方图

pop = np.random.randint(0,100,100)
plt.hist(pop,bins=20)
plt.title('直方图')
plt.show()

 

  5.3 条形图

index = [0,1,2,3,4]
value = [5,7,3,4,6]
plt.bar(index,value)
plt.show()

  水平条状图:plt.barh(index,value)

  多组数据的条形图:

data = {'series1':[1,2,4,3,5],
            'series2': [2, 4, 5, 2, 4],
            'series3': [3, 2, 3, 1, 3]}
df = pd.DataFrame(data)
df.plot(kind='bar')
plt.show()

如果需要构造数据堆积的图, 则使用:plt.bar(index,series2,color='b',bottom=series1)

5.4 饼图

data = {'series1': [1, 2, 4, 3, 5],
            'series2': [2, 4, 5, 2, 4],
            'series3': [3, 2, 3, 1, 3]}
df = pd.DataFrame(data)
# kind:类型,figsize:图像比例,autopct:计算百分比,shadow:阴影,explode:凸出
df['series1'].plot(kind='pie',figsize=(8,6),autopct='%1.1f%%',shadow=True,explode=[0.3,0,0,0,0])
plt.show()

  5.5 等值线图

x = np.arange(-2.0,2.0,0.01)
y = np.arange(-2.0,2.0,0.01)
X,Y = np.meshgrid(x,y)
def f(x,y):
    return (1-y**5+x**5)*np.exp(-x**2-y**2)
C = plt.contour(X,Y,f(X,Y),8,color='black')
plt.contourf(X,Y,f(X,Y),8,cmap=plt.cm.hot)
plt.clabel(C,inline=1,fontsize=10)
plt.colorbar()
plt.show()

 

5.6 极区图

theta = np.arange(0,2*np.pi,2*np.pi/8)
redii = np.array([4,7,5,3,1,5,6,7])
colors = np.array(['lightgreen','darkred','navy','brown','violet','plum','yellow','darkgreen'])
plt.axes(polar=True)
plt.bar(theta,redii,width=(2*np.pi/8),bottom=0.0,color=colors)
plt.show()

5.7 3D图

(1) 曲面图

fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-2,2,0.1)
Y = np.arange(-2,2,0.1)
X,Y = np.meshgrid(X,Y)
def f(x,y):
    return (1-y**5+x**5)*np.exp(-x**2-y**2)
ax.plot_surface(X,Y,f(X,Y),rstride=1,cstride=1,cmap=plt.cm.hot)
ax.view_init(elev=30,azim=125)
plt.show()

(2)3D散点图

    xs = np.random.randint(30,40,100)
    ys = np.random.randint(20, 30, 100)
    zs = np.random.randint(10, 20, 100)
    xs2 = np.random.randint(50, 60, 100)
    ys2 = np.random.randint(30, 40, 100)
    zs2 = np.random.randint(50, 70, 100)
    xs3 = np.random.randint(10, 30, 100)
    ys3 = np.random.randint(40, 50, 100)
    zs3 = np.random.randint(40, 50, 100)
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.scatter(xs,ys,zs)
    ax.scatter(xs2, ys2, zs2)
    ax.scatter(xs3, ys3, zs3)
    ax.set_label('X label')
    ax.set_label('Y label')
    ax.set_label('Z label')
    plt.show()

(3)3D条状图

    x = np.arange(8)
    y = np.random.randint(0,10,8)
    y2 = y+np.random.randint(0, 3, 8)
    y3 = np.random.randint(0, 3, 8)
    y4 = np.random.randint(0, 3, 8)
    y5 = np.random.randint(0, 3, 8)
    clr = ['lightgreen','darkred','navy','brown','violet','plum','yellow','darkgreen']
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.bar(x,y,0,zdir='y',color=clr)
    ax.bar(x, y2, 10, zdir='y', color=clr)
    ax.bar(x, y3, 20, zdir='y', color=clr)
    ax.bar(x, y4, 30, zdir='y', color=clr)
    ax.bar(x, y5, 40, zdir='y', color=clr)
    ax.set_label('X Axis')
    ax.set_label('Y Axis')
    ax.set_label('Z Axis')
    ax.view_init(elev=40)
    plt.show()

5.8 子图

    fig = plt.figure()
    ax = fig.add_axes([0.1,0.1,0.8,0.8])
    inner_ax = fig.add_axes([0.6,0.6,0.25,0.25])
    x1 = np.arange(10)
    y1 = np.array([1,2,7,1,5,2,4,2,3,1])
    x2 = np.arange(10)
    y2 = np.array([1,3, 4, 5, 4, 5, 2, 6,4,3])
    ax.plot(x1,y1)
    inner_ax.plot(x2,y2)
    plt.show()

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值