数据蛙数据分析每周作业Matplotlib

《莫烦Python》笔记 -- matplotlib部分

2018-12-31  本文已影响0人  小T数据站

1.1 为什么用Matplotlib

1.2 Matplotlib安装

Mac os 安装
Linx安装
Windows安装

安装Anaconda

2.1 基本用法

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook  # 进入交互模式,这条语句适用于jupter,在IPython中需运行%matplotlib

x = np.linspace(-1,1,50)
y = 2*x+1
plt.plot(x,y)
plt.show()
基本用法

2.2 figure图像

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2

plt.figure()
plt.plot(x,y1)
plt.show()
图2.2-1
plt.figure(num=3,figsize=(8,5)) # figsize用于设置画布大小
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--') 
plt.show()
图2.2-2

2.3 设置坐标轴1

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']) # 重新设置刻度标签
plt.show()
设置坐标轴1

2.4 设置坐标轴2

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))

new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
           ['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])
# 使用 '$ $' 为了获得一个更好看的文本格式, e.g. '$\pi$'

# gca = 'get current axis' gca的含义
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')         # (参数可设置为'top' | 'bottom' | 'both' | 'default' | 'none' )
ax.spines['bottom'].set_position(('data', 0)) # 将x轴放在y=0处

ax.yaxis.set_ticks_position('left')          # (参数可设置为'left' | 'right' | 'both' | 'default' | 'none')
ax.spines['left'].set_position(('data',0))  # 将Y轴放在x=0处
plt.show()
设置坐标轴2

2.5 Legend图例

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.xlim((-1, 2))
plt.ylim((-2, 3))

new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
# the "," is very important in here l1, = plt... and l2, = plt... for this step

plt.legend(loc='best') 
# 显示坐标轴,loc = 'best'表示会选择一个不会遮挡的它认为的最佳位置
# 你也可以指定位置,举例:upper right
'''
     'best' 
     'upper right' 
     'upper left' 
     'lower left' 
     'lower right' 
     'right'  
     'center left'  
     'center right' 
     'lower center'
     'upper center' 
      'center'    
'''
图2.5-1
 plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='best')
# 参数handle表示显示哪些图例,见下下个图,参数labels为图例命名
图2.5-2
plt.legend(handles=[l1,], labels=['up', 'down'],  loc='best')
图2.5-3

2.6 Annotation标注

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

x0 = 1
y0 = 2*x0 + 1  # 设置要标注的点
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5) # 绘制对应于x=1的虚线
plt.scatter(x0,y0, s=50, color='b') # 绘制标记的点

# 方法一
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")) 
  # % y0 表示将y0传递给s
  # 参数xy表示在何处做标注
  # 参数xycoords我自己理解的意思是作为后面参数设置的基点
  # xytext是标注的文本基于textcoords做偏移的尺度,此例是x向右移30,y向下移30

# 方法二
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

plt.show()
标注过的图

2.7 tick能见度

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure(figsize=(8,4))
plt.plot(x, y, linewidth=10, zorder=1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))


for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.8, zorder=2))  # 参数alpha设置透明度
plt.show()
设置能见度

3.1 Scatter散点图

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

n = 1024    # 设置数据量的大小
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y, X)    # 对点进行配色

plt.scatter(X, Y, s=75, c=T, alpha=.5)  # s:size,c:color
plt.xlim(-1.5, 1.5)
plt.xticks(())  # 去掉x轴的刻度标签
plt.ylim(-1.5, 1.5)
plt.yticks(())  # 去掉y轴的刻度标签

plt.show()
散点图

3.2 Bar柱形图

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)

plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')

for x, y in zip(X, Y1):
    # ha: horizontal alignment  ha:左右对齐方式
    # va: vertical alignment   va:上下对齐方式
    plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')

for x, y in zip(X, Y2):
    # ha: horizontal alignment
    # va: vertical alignment
    plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')

plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())

plt.show()
柱形图

3.3 Coutours等高线图

import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    # 计算等高线的函数
    return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x, y)

plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)


C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidths=.5)

plt.clabel(C, inline=True, fontsize=10)

plt.xticks(())
plt.yticks(())
plt.show()
等高线图

3.4 Image图片

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

# image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
"""
查看有关参数interpolation的信息:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
关于参数origin的解释,请查看:
http://matplotlib.org/examples/pylab_examples/image_origin.html
"""
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.92)

plt.xticks(())
plt.yticks(())
plt.show()
图3.4

3.5 3D数据

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook

fig = plt.figure()
ax = Axes3D(fig)

X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R) # 高度的值

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
plt.show()
3D图
ax.contourf(X, Y, Z, zdir='z', offset=-1, cmap=plt.get_cmap('rainbow'))
3D图with等高图

4.1 Subplot多合一显示

import matplotlib.pyplot as plt
%matplotlib notebook

plt.figure(figsize=(6, 4))
# plt.subplot(行数,列数, 图绘制的位置)
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])

plt.subplot(222)
plt.plot([0, 1], [0, 2])

plt.subplot(223)
plt.plot([0, 1], [0, 3])

plt.subplot(224)
plt.plot([0, 1], [0, 4])

plt.tight_layout()
多合一绘图1
plt.figure(figsize=(6, 4))

plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])

plt.subplot(234)
plt.plot([0, 1], [0, 2])

plt.subplot(235)
plt.plot([0, 1], [0, 3])

plt.subplot(236)
plt.plot([0, 1], [0, 4])


plt.tight_layout()
plt.show()
多合一绘图2

4.3 Subplot分格显示

# 方法一: subplot2grid
import matplotlib.pyplot as plt
%matplotlib notebook

plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)  # 画布分为3行3列,此图从0行0列处,列宽为3,行宽默认为1
ax1.plot([1, 2], [1, 2])
ax1.set_title('ax1_title') # 设置子图的标题,其他参数可以类推
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)# 画布分为3行3列,此图从1行2列处,列宽默认为1,行宽为2
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
ax5 = plt.subplot2grid((3, 3), (2, 1))
分格显示--法一
# 方法二: gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
%matplotlib notebook

plt.figure()
gs = gridspec.GridSpec(3, 3)

ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[-1, 0])
ax10 = plt.subplot(gs[-1, -2])
分格显示--法二
# 方法三: 较简单的法子
import matplotlib.pyplot as plt
%matplotlib notebook
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])

plt.tight_layout()
plt.show()
分格显示--法三

4.3 图中图

import matplotlib.pyplot as plt
%matplotlib notebook

fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]

left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 # 这些数是相对整个figure的百分数
ax1 = fig.add_axes([left, bottom, width, height])  # 设置主图法坐标轴相对位置
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')

ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25])  # 内置小图的位置
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')


#  另一种绘制图中图的方法
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')

plt.show()
图中图

4.4 次坐标轴

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()    # 生成ax1坐标轴的镜像
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()
次坐标轴

5.1 Animation动画

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x + i/10.0))  # update the data
    return line,

def init():
    line.set_ydata(np.sin(x))
    return line,

ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init,
                              interval=20, blit=False)
plt.show()
标注动画.gif
上一篇 下一篇

猜你喜欢

热点阅读