Matplotlib

https://matplotlib.org/index.html

显示多个图像

import matplotlib.pyplot as plt
import numpy as np

# 多个figure
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

# 使用figure()函数重新申请一个figure对象
# 注意,每次调用figure的时候都会重新申请一个figure对象
plt.figure()
# 第一个是横坐标的值,第二个是纵坐标的值
plt.plot(x, y1)

# 第一个参数表示的是编号,第二个表示的是图表的长宽
plt.figure(num = 3, 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

# 从[-1,1]中等距去50个数作为x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

# 请求一个新的figure对象
plt.figure()
# 第一个是横坐标的值,第二个是纵坐标的值
plt.plot(x, y1) 

# 设置轴线的lable(标签)
plt.xlabel("I am x")
plt.ylabel("I am y")

plt.show()

加粗样式

同时绘制多条曲线

import matplotlib.pyplot as plt
import numpy as np

# 从[-1,1]中等距去50个数作为x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
# num表示的是编号,figsize表示的是图表的长宽
plt.figure(num = 3, figsize=(8, 5)) 
plt.plot(x, y2)
# 设置线条的样式
plt.plot(x, y1, 
     color='red', # 线条的颜色
     linewidth=1.0, # 线条的粗细
     linestyle='--' # 线条的样式
    )

# 设置取值参数范围
plt.xlim((-1, 2)) # x参数范围
plt.ylim((1, 3)) # 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'$readly\ good$'])

# gca = 'get current axis'
ax = plt.gca()
# 将右边和上边的边框(脊)的颜色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 绑定x轴和y轴
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 定义x轴和y轴的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

plt.show()

在这里插入图片描述

多条曲线之曲线说明

import matplotlib.pyplot as plt
import numpy as np

# 从[-1,1]中等距去50个数作为x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

# 第一个参数表示的是编号,第二个表示的是图表的长宽
plt.figure(num = 3, figsize=(8, 5)) 
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

# 设置取值参数
plt.xlim((-1, 2))
plt.ylim((1, 3))

# 设置lable
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'$readly\ good$'])


l1, = plt.plot(x, y2, 
        label='aaa'
       )
l2, = plt.plot(x, y1, 
        color='red', # 线条颜色
        linewidth = 1.0, # 线条宽度
        linestyle='-.', # 线条样式
        label='bbb' #标签
       )

# 使用legend绘制多条曲线
plt.legend(handles=[l1, l2], 
      labels = ['aaa', 'bbb'], 
      loc = 'best'
     )

plt.show()

在这里插入图片描述

多条曲线通用例子

def init_colors():
  return ['blue', 'red', 'green', 'black', 'pink', 'purple', 'gray', 'yellow']

def show_graph(data, save_png_name=None, colors=init_colors()):
  """
  绘制折线图
  :param data: 数据格式:{label:{X:Y}, label:{X:Y}...}
  :param save_png_name:保存的图片的名字
  :param colors: 颜色列表
  :return:
    None
  """
  # 解决中文显示乱码的问题,不用中文就不需要设置了
  my_font = font_manager.FontProperties(fname="/自己补充路径/IOS8.ttf")
  
  plt.figure(figsize=(14, 6))
  plts = []
  labels = []
  for index, label in enumerate(data.keys()):
    if label is 'rotate':
      continue
    color = colors[index]
    X = data.get(label).keys()
    Y = [data.get(label).get(x) for x in X]
    temp, = plt.plot(X, Y, color=color, label=label)
    plts.append(temp)
    labels.append(label)
  plt.legend(handles=plts, labels=labels, prop=my_font)
  plt.show()
  if save_png_name is not None:
    plt.savefig(save_png_name)

在这里插入图片描述在这里插入图片描述

散点图

import matplotlib.pyplot as plt
import numpy as np

n = 1024
# 从[0]
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(X, Y)

plt.scatter(np.arange(5), np.arange(5))

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

plt.show()

在这里插入图片描述

条形图

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.figure(figsize=(12, 8))
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, 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, 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()

在这里插入图片描述

contour等高线图

import matplotlib.pyplot as plt
import numpy as np

def get_height(x, y):
  # the height function
  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.figure(figsize=(14, 8))

# use plt.contourf to filling contours
# X, Y and value for (X, Y) point

# 横坐标、纵坐标、高度、 、透明度、cmap是颜色对应表
# 等高线的填充颜色
plt.contourf(X, Y, get_height(X, Y), 16, alpah=0.7, cmap=plt.cm.hot) 

# use plt.contour to add contour lines
# 这里是等高线的线
C = plt.contour(X, Y, get_height(X, Y), 16, color='black', linewidth=.5)

# adding label
plt.clabel(C, inline=True, fontsize=16)

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(figsize=(12, 8))
ax = Axes3D(fig)

# 生成X,Y
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)

# 绘图
# rstride(row)和cstride(column)表示的是行列的跨度
ax.plot_surface(X, Y, Z, 
        rstride=1, # 行的跨度
        cstride=1, # 列的跨度
        cmap=plt.get_cmap('rainbow') # 颜色映射样式设置
        )

# offset 表示距离zdir的轴距离
ax.contourf(X, Y, Z, zdir='z', offest=-2, cmap='rainbow')
ax.set_zlim(-2, 2)

plt.show()

在这里插入图片描述

Subplot多合一显示

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

# 将整个figure分成两行两列
plt.subplot(2, 2, 1)
# 第一个参数表示X的范围,第二个是y的范围
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.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值