最近跟学了莫烦python
记录一下可视化的代码*
首先我用的是spyder,关于绘图最好能在新的窗口显示结果,设置如下:
spyder->Tools->Preferences->IPython console->Graphics->Backend改成‘"Qt5"
在这里插入图片描述
part 1基本绘图

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,50)
y = 2 * x + 1
plt.plot(x,y)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,50)
y = x**2 + 1
plt.plot(x,y)
plt.show()

figure

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,50)
y1 = 2 * x + 1
y2 = x**2 + 1

plt.figure()
plt.plot(x,y1)

plt.figure(num = 2, figsize=(8,5))
plt.plot(x,y2)

plt.plot(x,y1,color = 'red', linewidth = 1.0, linestyle = '--')
plt.show()

在坐标轴上标注

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure(figsize=(10,10))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

#设置范围
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('x')
plt.ylabel('y')

new_sticks = np.linspace(-1,2,5)
print(new_sticks)
plt.xticks(new_sticks)
#在y轴某点标注
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'reallybad', r'bad', r'normal', r'good', r'reallygood'])
plt.show()

spines设置边框

#part 5 
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure(figsize=(8,8))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

#设置范围
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('x')
plt.ylabel('y')

new_sticks = np.linspace(-1,2,5)
print(new_sticks)
plt.xticks(new_sticks)
#在y轴某点标注
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'reallybad', r'bad', r'normal', r'good', r'reallygood'])

# gca = 'get current axis'
ax = plt.gca()
ax.spines['right'].set_color('red')
ax.spines['top'].set_color('blue')
ax.spines['bottom'].set_color('yellow')
#x轴
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
#y轴
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data'),0)
plt.show()

legend 添加图例

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure(figsize=(8,8))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

#设置范围
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('x')
plt.ylabel('y')

new_sticks = np.linspace(-1,2,5)
print(new_sticks)
plt.xticks(new_sticks)
#在y轴某点标注
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'reallybad', r'bad', r'normal', r'good', r'reallygood'])

l1, = plt.plot(x, y1, label = 'linear line')
l2, = plt.plot(x, y2, color = 'red', linewidth = 1.0, linestyle = '--', label = 'square line' )

plt.legend(loc = 'upper right')
 plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='best')
 the "," is very important in here l1, = plt... and l2, = plt... for this step

# plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='best')
plt.show()


"""legend( handles=(line1, line2, line3),
           labels=('label1', 'label2', 'label3'),
           'upper right')
    The *loc* location codes are::
          'best' : 0,          (currently not supported for figure legends)
          'upper right'  : 1,
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,"""

在某点做虚线垂直x轴

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 2*x + 1

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

ax = plt.gca()
ax.spines['right'].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)#[x0,x0]x轴上从x0到x0,  [0, y0]y轴上0到x0 
plt.scatter(x0, y0, s = 50, color = 'b' )  #s 散点的大小

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"))

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

tick 能见度

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure()
plt.plot(x, y, linewidth=10, zorder=1)      # set zorder for ordering the plot in plt 2.0.2 or higher
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)
    # set zorder for ordering the plot in plt 2.0.2 or higher
    label.set_bbox(dict(facecolor='y', edgecolor='r', alpha=0.8, zorder=2))
#alpha 透明度
plt.show()

Scatter 散点图

import matplotlib.pyplot as plt
import numpy as np
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y,X)
#T1 = np.arctan(X)
#T2 = np.arctan(Y)
#plt.scatter(X,Y,s = 75, c = T, alpha =0.5)
#plt.scatter(X,Y, s = 75, c = T, alpha =0.5)
plt.scatter(X, Y, s = 75, c = T, alpha =0.5)
#s  点的大小   c  color   alpha 透明度


plt.xlim(-1.5, 1.5)
plt.xticks(())  # ignore xticks
plt.ylim(-1.5, 1.5)
plt.yticks(())  # ignore yticks

plt.show()

Bar 柱形图

import matplotlib.pyplot as plt
import numpy as np
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  横向对齐
#    # va: vertical alignment    纵向对齐
#    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()

等高线

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)

# use plt.contourf to filling contours
# 颜色填充。使用函数plt.contourf把颜色加进去,位置参数分别为:X, Y, f(X,Y)。透明度0.75,并将 f(X,Y) 的值对应到color map的暖色组中寻找对应颜色
plt.contourf(X, Y, f(X, Y), 8 , alpha = 0.7, cmap = plt.cm.hot)
#等高线绘制.   8代表等高线的密集程度,如果是0,则图像被一分为二
C = plt.contour(X, Y, f(X, Y), 8 , colors = 'black', linewidth = 0.5)
#inline控制是否将Label画在线里面,字体大小为10
plt.clabel(C,inline = True, fontsize = 10)

plt.xticks(())
plt.yticks(())
plt.show()

Image图片

import matplotlib.pyplot as plt
import numpy as np
a = np.array([0.313660827978,0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)

"""
for the value of "interpolation", check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
for the value of "origin"= ['upper', 'lower'], check this:
http://matplotlib.org/examples/pylab_examples/image_origin.html
"""

#interpolation='nearest' 内插法选择‘nearest’
#cmap 即color map hot暖色,bone冷色, 
#origin='lower'代表的就是选择的原点的位置。
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
#shrink参数,使colorbar的长度变短为原来的92%
plt.colorbar(shrink=.92)
#xticks= ()即不标注坐标轴上各点
plt.xticks(())
plt.yticks(())
plt.show()

3D数据

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

fig = plt.figure()
ax = Axes3D(fig)
# X, Y value
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)
# height value
Z = np.sin(R)
#图1,3D
#rstride 和 cstride 分别代表 row 和 column 的跨度。
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
"""
============= ================================================
        Argument      Description
        ============= ================================================
        *X*, *Y*, *Z* Data values as 2D arrays
        *rstride*     Array row stride (step size), defaults to 10
        *cstride*     Array column stride (step size), defaults to 10
        *color*       Color of the surface patches
        *cmap*        A colormap for the surface patches.
        *facecolors*  Face colors for the individual patches
        *norm*        An instance of Normalize to map values to colors
        *vmin*        Minimum value to map
        *vmax*        Maximum value to map
        *shade*       Whether to shade the facecolors
        ============= ================================================
"""

#图2, 投影
#如果 zdir 选择了z,那么效果将会是对于 XY 平面的投影
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
"""
==========  ================================================
        Argument    Description
        ==========  ================================================
        *X*, *Y*,   Data values as numpy.arrays
        *Z*
        *zdir*      The direction to use: x, y or z (default)
        *offset*    If specified plot a projection of the filled contour通俗来说,就是控制投影的位置,这里下面的代码ax.set_zlim(-2, 2)将底部设为-2,offset = -2就能刚好投影到底部
                    on this position in plane normal to zdir
        ==========  ================================================
"""

ax.set_zlim(-2, 2)

plt.show()

subplot 多合一显示

import matplotlib.pyplot as plt
import numpy as np
plt.figure(num=1, figsize=(6 , 4))
plt.subplot(2,2,1)
plt.plot([0, 1],[0, 1])

plt.subplot(2,2,2)
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()

plt.figure(num=2, figsize=(6 , 4))
# plt.subplot(n_rows, n_cols, plot_num)
plt.subplot(2, 1, 1)
# figure splits into 2 rows, 1 col, plot to the 1st sub-fig
plt.plot([0, 1], [0, 1])
'''第4个位置放第2个小图. 上一步中使用plt.subplot(2,1,1)将整个图像窗口分为2行1列, 
第1个小图占用了第1个位置, 也就是整个第1行.
 这一步中使用plt.subplot(2,3,4)将整个图像窗口分为2行3列, 
 于是整个图像窗口的第1行就变成了3列, 也就是成了3个位置, 
 于是第2行的第1个位置是整个图像窗口的第4个位置.'''
plt.subplot(234)
# figure splits into 2 rows, 3 col, plot to the 4th sub-fig
plt.plot([0, 1], [0, 2])

plt.subplot(235)
# figure splits into 2 rows, 3 col, plot to the 5th sub-fig
plt.plot([0, 1], [0, 3])

plt.subplot(236)
# figure splits into 2 rows, 3 col, plot to the 6th sub-fig
plt.plot([0, 1], [0, 4])

plt.tight_layout()表示紧凑显示图像
plt.tight_layout()
plt.show()

Subplot 分格显示

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
 method 1: subplot2grid
#########################
plt.figure(num = 1)
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)  # stands for axes
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)
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))



plt.figure(num = 2)
gs = gridspec.GridSpec(3, 3)
# use index from 0
ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[2, 0])
ax10 = plt.subplot(gs[2, 1])

# method 3: easy to define structure
####################################
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])

plt.tight_layout()

图中图

import matplotlib.pyplot as plt
import numpy as np
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

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])  # inside axes
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')

# different method to add axes
####################################
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()

次坐标轴

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()   #采用默认值

ax2 = ax1.twinx()  # mirror the 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() 

animation 动图

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as 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,


# Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
                              interval=25, blit=True)
plt.show()

画箭头

import matplotlib.pyplot as plt
import numpy as np
def f(x):
    return x * np.cos(np.pi * x)
x = np.arange(-1.0, 2.0, 0.1)
fig= plt.plot(x,f(x))
plt.annotate('local min',xy=(-0.28,-0.13),xytext=(-0.7,-0.5),arrowprops=dict(arrowstyle="->"))
plt.annotate('global min',xy=(1,-1),xytext=(1,0.3),arrowprops=dict(arrowstyle="->"))```

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐