Matplotlib数据可视化库

来自CloudWiki
跳转至: 导航搜索

安装

绘图

折线图

   # 折线图
   
   import random
   import matplotlib.pyplot as plt
   import matplotlib as mpl
   mpl.rcParams['font.family'] = 'SimHei'  # 设置字体为黑体
   mpl.rcParams['axes.unicode_minus'] = False  # 设置在中文字体是能够正常显示负号(“-”)
   # import numpy as np
   # 设置图片大小
   # plt.figure(figsize =(20,10), dpi=80)
   x = range(0, 80)
   y = [random.randint(20, 100) for i in range(0,80)]
   
   print(y)
   print(x)
   
   # 设置xy轴标签
   plt.xlabel("时间")
   plt.ylabel("温度")
   plt.title('标题冲冲冲')
   # 折线图
   plt.plot(x, y)
   # # 设置x轴刻度
   
   xle = [i for i in range(0, 80, 4)]
   xlename = ["10点%d分"%i for i in range(0, 80, 4)]
   # rotation=90 旋转90度
   plt.xticks(xle, xlename, rotation=270)
   # # 设置y轴刻度
   # plt.yticks()
   
   # # 设置图片保存路径
   # # # plt.savefig('./tl1.png')
   plt.show()

X11.png

散点图

   # 散点图
   
   import random
   import matplotlib.pyplot as plt
   import matplotlib as mpl
   mpl.rcParams['font.family'] = 'SimHei'  # 设置字体为黑体
   mpl.rcParams['axes.unicode_minus'] = False  # 设置在中文字体是能够正常显示负号(“-”)
   x = [random.randint(10,30) for i in range(0,100)]
   x2 = [random.randint(10,30) for i in range(0,100)]
   y = [i+10 for i in x]
   y2 = [i+5 for i in x2]
   # 散点图
   x_le = range(10,30,3)
   x_leinfo = ["数值%d"%i for i in range(10,30,3)]
   # 设置x轴
   plt.xticks(x_le, x_leinfo, rotation=270)
   
   plt.xlabel("x轴")
   plt.ylabel('y轴')
   plt.title("散点图")
   plt.scatter(x, y)
   plt.scatter(x2, y2)
   plt.show()

X22.png

条形图

   # 条形图
   # 多个条形图的综合使用
   
   import random
   import matplotlib.pyplot as plt
   import matplotlib as mpl
   mpl.rcParams['font.family'] = 'SimHei'  # 设置字体为黑体
   mpl.rcParams['axes.unicode_minus'] = False  # 设置在中文字体是能够正常显示负号(“-”)
   x_info = ['战狼2', '速度与激情8', '功夫瑜伽', '最后的骑士', '摔跤吧爸爸', '加勒比海盗']
   # x坐标轴位置
   x = range(0, 30, 5)
   x_2 = [i+1 for i in x]
   x_3 = [i+2 for i in x]
   
   # 设置x轴标签
   plt.xticks(x_2, x_info)
   
   # y轴数值
   y_1 = [56.01, 26.94, 17.54, 23.24, 35.52, 15.58]
   y_2 = [78.28, 56.94, 35.54, 27.24, 25.52, 12.58]
   y_3 = [81.01, 59.94, 33.54, 65.24, 15.52, 10.58]
   plt.bar(x, y_1, width=1, label="10.1日")
   plt.bar(x_2, y_2, width=1, label="10.2日")
   plt.bar(x_3, y_3, width=1, label="10.3日")
   # 设置label图例
   plt.legend()
   
   plt.xlabel("电影名称")
   plt.ylabel("票房(亿)")
   plt.title("电影票房统计")
   plt.show()

X33.png

直方图

    # 直方图
    
    import random
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    # 设置网格
    plt.grid()
    
    mpl.rcParams['font.family'] = 'SimHei'  # 设置字体为黑体
    mpl.rcParams['axes.unicode_minus'] = False
    x = [91, 32, 65, 64, 65, 79, 64, 62, 62, 32, 49, 16, 32, 54, 64, 62, 15, 62, 37, 85, 96, 63, 52, 63,
         41, 36, 63, 52, 35, 50]
    print(x.index(96))
    # 计算数组
    
    d = 5  # 组距
    # 当max(x)-min(x)的值能整除d时不会出现偏移  如果不能被整除时会出现偏移
    group = ((max(x)-min(x))%d)
    print(group)
    plt.hist(x, group)
    
    # 设置x轴刻度
    plt.xticks(range(min(x), max(x)+d, d))
    plt.show()