散点图-scatter
散点图显示两组数据的值,每个点的坐标位置由变量的值决定由一组不连接的点完成,用于观察两种变量的相关
1 import numpy as np 2 import matplotlib.pyplot as plt #导入绘图模块 3 4 height = [161, 170, 182, 175, 173, 165] 5 weight = [50, 58, 80, 70, 69, 55] 6 7 plt.scatter(height, weight) 8 N = 1000 9 x = np.random.randn(N) 10 # y1 = np.random.randn(N) 11 y1 = -x + np.random.randn(N)*0.5 12 13 14 # 绘制散点图的命令行 15 plt.scatter(x, y1, s=100, c='r', marker='o', alpha=0.5) 16 # s表示点的面积,c表示点的颜色,marker表示点的形状,alpha表示点的透明度 17 18 plt.show()
折线图
折线图是用直线段将各数据连接起来组成的图形常用来观察数据随时间变化的趋势
1 import numpy as np 2 import matplotlib.pyplot as plt 3 import matplotlib.dates as mdates 4 5 x = np.linspace(-10, 10, 100) 6 7 # y = x**2 8 y = np.sin(x) 9 10 plt.plot(x, y, linestyle='-.', color='g', marker='^') 11 # 折线图的基本绘制命令行,linestyle为要画的线型,color为线的颜色,marker为点的形状 12 # 在matplotlib官网中,有关于线型,颜色,点的形状的全面介绍 13 14 plt.show()
条形图
以长方形的长度为变量的统计图表,用来比较多个项目分类的数据大小,通常利用于较小的数据集分析
条形图可以以单列,并列,层叠方式画图
1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 # 单列模式 5 N = 5 6 y = [20, 10, 30, 25, 15] 7 index = np.arange(N) 8 9 # plt.bar(x=index, height=y, width=0.5, color='r') 10 # x表示的是x轴上对应的第几个条形,height表示的y轴上对应条形的高度, 11 # width表示条形的 宽度 12 plt.bar(index, y, 0.5, color='r') # x=,height=,width=,可以省略 13 14 15 # 条形图也可以横着放 16 # x需要赋0值,bottom表示条形块的底部即对应纵轴上的坐标, 17 # width表示条形块横着放的高度,相当于横轴上(横向)的宽度, 18 # height表示条形块纵向的宽度,orientation='horizontal'表示要画横向的条形图 19 pl = plt.bar(x=0, bottom=index, color='red', width=y, height=0.5, 20 orientation='horizontal') 21 # 横向条形图有第二种方式,这里的y轴应赋值第几个条形快即index 22 # pl = plt.barh(y=index, color='red', width=y,) 23 24 25 plt.show()
1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 # 并列式绘条形图,将两个条形图共用一个坐标轴,并列的画在一起 5 index = np.arange(4) 6 sales_BJ = [52,55,63,53] 7 sales_SH = [44,66,55,41] 8 9 bar_width = 0.3 10 plt.bar(index,sales_BJ,bar_width,color='b') 11 12 # 这个并列的条形图的横轴上的坐标可以用index+bar_width来表示 13 # 目的是不与第一个重叠 14 plt.bar(index+bar_width,sales_SH,bar_width,color='r') 15 16 plt.show()
1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 5 # 层叠绘图 6 index = np.arange(4) 7 sales_BJ = [52,55,63,53] 8 sales_SH = [44,66,55,41] 9 10 bar_width = 0.3 11 plt.bar(index,sales_BJ,bar_width,color='b') 12 13 # 第二个要层叠的对象需要加bottom=sales_BJ,表示层叠底部的对象是上一个 14 plt.bar(index,sales_SH,bar_width,color='r',bottom=sales_BJ) 15 16 plt.show()