1. Matplotlib使用

    技术2022-07-10  118

    示例1.绘制原始折线图

    # 展示上海市最近一周的天气 import matplotlib.pyplot as plt # 1. 创建画布 plt.figure(figsize=(20,8),dpi=80) # 2. 绘制折线图 plt.plot([1,2,3,4,5,6,7],[17, 17, 18, 15, 11, 11, 13]) # 3. 保存图片 plt.savefig("test.png")

    示例2. 完善原始折线图

    # 画出北京和上海11点到12点1小时内每分钟的温度变化折线图,温度范围在15度~18度 import matplotlib.pyplot as plt import random # 1. 准备数据 x=range(60) y_shanghai=[random.uniform(15,18)for i in x] y_beijing=[random.uniform(1,3)for i in x] # 2. 创建画布 plt.figure(figsize=(20,8),dpi=80) # 3. 绘制折线图 plt.plot(x,y_shanghai,color='b', label="上海") plt.plot(x,y_beijing,color='r', label="北京") # 4. 辅助显示层 # 显示图例 plt.legend(loc="best") # 修改x,y刻度 x_label=["11点:{}".format(i) for i in x] plt.xticks(x[::5],x_label[::5]) plt.yticks(range(40)[::5]) # 添加网格 plt.grid(True, linestyle="--",alpha=0.5) # 添加x,y轴标题 plt.xlabel('时间') plt.ylabel('气温') plt.title('11点到12点的气温变化') # 最后,显示图像 plt.show()

    示例3. 在多个坐标系中绘制折线图

    # 1. 准备数据 x=range(60) y_shanghai=[random.uniform(15,18)for i in x] y_beijing=[random.uniform(1,3)for i in x] # 2. 创建画布 # 面向对象画图 matplotlib.pyplot.subplots(nrows=1, ncols=1, **fig_kw) 创建一个带有多个axes(坐标系/绘图区)的图 fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8), dpi=80) #nrow=1,ncols2代表1行2列的绘图区的画布 # 3. 绘制折线图 axes[0].plot(x,y_shanghai,color='b', label="上海") axes[1].plot(x,y_beijing,color='r', label="北京") # 4. 辅助显示层 # 显示图例 axes[0].legend(loc="best") axes[1].legend(loc="best") # 修改x,y刻度 x_label=["11点:{}".format(i) for i in x] y_ticks=range(40) axes[0].set_xticks(x[::10]) # 这里注意刻度和刻度的名称必须数量一致 axes[0].set_xticklabels(x_label[::10]) #注意,面向对象刻度和刻度单位的设置是set_xticks和set_xticklabels两个方法!! axes[0].set_yticks(y_ticks[::5]) # [::5]代表步长为5取值 axes[1].set_xticks(x[::10]) axes[1].set_xticklabels(x_label[::10]) axes[1].set_yticks(y_ticks[::5]) # 添加网格 axes[0].grid(True, linestyle="--",alpha=0.5) axes[1].grid(True, linestyle="--",alpha=0.5) # 添加x,y轴标题 axes[0].set_xlabel('时间') axes[0].set_ylabel('气温') axes[0].set_title('上海11点到12点的气温变化') axes[1].set_xlabel('时间') axes[1].set_ylabel('气温') axes[1].set_title('北京11点到12点的气温变化') # 最后,显示图像 plt.show()

    示例4 折线图画函数图像

    # 画y=sinx函数的图像 import numpy as np # 1)准备数据 #在-10到10之间生成1000个均布(等距)的数,当点很密看起来就会连续的 x = np.linspace(-10, 10, 1000) y = np.sin(x) # 2)创建画布 plt.figure(figsize=(20, 8), dpi=100) # 3)绘制函数图像 plt.plot(x, y) # 添加网格显示 plt.grid() # 4)显示图像 plt.show()

    示例5 散点图绘制

    # 0)import matplotlib.pyplot as plt # 1)准备数据,x是房屋面积,y是房屋价格 x = [225.98, 247.07, 253.14, 457.85, 241.58, 301.01, 20.67, 288.64, 163.56, 120.06, 207.83, 342.75, 147.9 , 53.06, 224.72, 29.51, 21.61, 483.21, 245.25, 399.25, 343.35] y = [196.63, 203.88, 210.75, 372.74, 202.41, 247.61, 24.9 , 239.34, 140.32, 104.15, 176.84, 288.23, 128.79, 49.64, 191.74, 33.1 , 30.74, 400.02, 205.35, 330.64, 283.45] # 2)创建画布 plt.figure(figsize=(20, 8), dpi=100) # 3)绘制散点图 plt.scatter(x, y) #散点图用scatter方法 # 4)显示图像 plt.show()
    Processed: 0.011, SQL: 9