数据可视化——matplotlib
散点图
散点图可以用来判断数据的相关性
import numpy as np
import matplotlib.pyplot as plt
height=[161,170,182,175,173,165]
weight=[50,58,80,70,69,55]
# s代表点的大小,c代表颜色, marker代表点的形状, alpha代表透明度
plt.scatter(height,weight, s = 20, c = 'b', marker = 'o', alpha = 0.5)
plt.show()
折线图
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
x=np.linspace(-10,10,100)
y=x**2
plt.plot(x,y,linestyle = '-', color = 'green', marker = '<')
plt.show()
# plot_date函数可以自动识别date数据并将其转换成相应的时间日期
plt.plot_date(date,close)
plt.show()
条形图
import numpy as np
import matplotlib.pyplot as plt
y=[20,10,30,25,15]
index = np.arange(5)
p1 = plt.bar(index, height=y,width=0.5,bottom=100,color='red')
plt.show()
# orientation = 'horizontal'意味着画水平的条形图,width, index等需要灵活变换
p2 = plt.bar(bottom=index, width=y,height=0.5,orientation='horizontal')
plt.show()
# barh也是画水平条形图
p3=plt.barh(bottom=index,width=y,height=0.5)
plt.show()
index=np.arange(4)
sales_BJ=[52,55,63,53]
sales_SH=[44,66,55,41]
bar_width=0.3
plt.bar(index,sales_BJ,bar_width,color='b')
# index+bar_width画两条并列的条形图
plt.bar(index+bar_width,sales_SH,bar_width,color='r')
plt.show()
# bottom=sales_BJ画出层叠图
plt.bar(index,sales_BJ,bar_width,color='b')
plt.bar(index,sales_SH,bar_width,color='r',bottom=sales_BJ)
plt.show()
直方图
import numpy as np
import matplotlib.pyplot as plt
mu = 100 # mean of distribution
sigma = 20 # standard deviation of distribution
x = mu + sigma * np.random.randn(2000)
# normed = True/False 意味着是否对数据进行标准化
plt.hist(x, bins=10,color='red',normed=True)
plt.hist(x, bins=50,color='green',normed=False)
plt.show()
# 两个变量的直方图,利用颜色深浅表示频率大小
x = np.random.randn(1000)+2
y = np.random.randn(1000)+3
# 利用hist2d函数画双变量直方图
plt.hist2d(x, y, bins=40)
plt.show()
饼状图
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
# Some data
labels = 'A', 'B', 'C', 'D'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
# 让x,y轴的比例为1:1,这样画出的饼状图是一个圆而不是椭圆
plt.axes(aspect=1)
explode = (0, 0.05, 0, 0)
# autopct将每块所占比例用格式化字符串表示出来,explode表示每块离中心的距离来突出显示,shadow = True每块会加阴影,更有立体感
plt.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', explode = explode, shadow=True)
plt.show()
箱型图
箱形图是一种用作显示一组数据分散情况资料的统计图,上边缘、上四分位数、中位数、下四分位数、下边缘、异常值
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100)
data = np.random.normal(size=1000, loc=0.0, scale=1.0)
# sym = 'o'用来调整异常值点的形状, whis = 1.5代表虚线的长度
plt.boxplot(data,sym='o',whis=1.5)
plt.show()
# 同时显示多个箱形图
data = np.random.normal(size=(100, 4), loc=0.0, scale=1.0)
labels = ['A','B','C','D']
plt.boxplot(data, labels=labels)
plt.show()
颜色与形状
import numpy as np
import matplotlib.pyplot as plt
#默认情况
y=np.arange(1,5)
plt.plot(y)
plt.show()
#调整颜色
y=np.arange(1,5)
plt.plot(y, color = 'g')
plt.plot(y, color = '0.5')
plt.plot(y, color = 'FF00FF')
plt.plot(y+1,color=(0.1,0.2,0.3));
plt.show()
#线型
y=np.arange(1,5)
plt.plot(y,'--');
plt.plot(y+1,'-.');
plt.plot(y+2,':');
plt.plot(y+3,'-');
plt.show()
#点形状
# 指定marker时, 例如marker = 'o'会画出线段,若不指定则只显示点
y=np.arange(1,5)
plt.plot(y,marker = 'o');
plt.plot(y+1,'D');
plt.plot(y+2,'^');
plt.plot(y+3,'s');
plt.plot(y+4,'p');
plt.plot(y+5,'x');
plt.show()
# 可将颜色点型线型写成一个字符串
y=np.arange(1,5)
plt.plot(y,'cx--');
plt.plot(y+1,'kp:');
plt.plot(y+2,'mo-.');
plt.show()
matplotlib面向对象
子图
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(1,100)
# 第一个参数代表子图总行数,第二个参数代表子图总列数,第三个1代表位置
plt.subplot(221)
# 下面方法与上面方法结果一样
fig = pli.figure() # 生成figure对象
ax = fig.add_subplot(221)
plt.plot(x,x)
plt.subplot(222)
plt.plot(x,-x)
plt.subplot(223)
plt.plot(x,x*x)
plt.subplot(224)
plt.plot(x,np.log(x))
plt.show()
多图
import matplotlib.pyplot as plt
fig1=plt.figure()
ax1=fig1.add_subplot(111)
ax1.plot([1,2,3],[3,2,1])
fig2=plt.figure()
ax2=fig2.add_subplot(111)
ax2.plot([1,2,3],[1,2,3])
plt.show()
网格
import numpy as np
import matplotlib.pyplot as plt
y=np.arange(1,5)
plt.plot(y,y*2)
#交互中打开网格
plt.grid(True)
plt.show()
#交互中关闭网格
plt.grid()
import numpy as np
import matplotlib.pyplot as plt
y=np.arange(1,5)
plt.plot(y,y*2)
# 定制网格,color改变颜色,linestyle改变网格线型,linewidth改变网格线的粗细
plt.grid(True,color='g',linestyle='-',linewidth='2')
plt.show()
#Object Oriented
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,10,1)
y=np.random.randn(len(x))
fig=plt.figure() # 生成figure对象
ax=fig.add_subplot(111) # 生成坐标轴对象
l,=plt.plot(x,y)
ax.grid(color='g')
plt.show()
图例
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(1,11,1)
y=x*x
# label自定义线的名字
plt.plot(x,x*2,label='Normal')
plt.plot(x,x*3,label='Fast')
plt.plot(x,x*4,label='Faster')
# loc代表图例的位置参数(1,2,3,4分别为右上角、左上角、左下角、右下角,0代表自动选取最优位置)
# ncol代表图例的列数
plt.legend(loc=0,ncol=2)
plt.show()
#方式2
plt.plot(x,x*2)
plt.plot(x,x*3)
plt.plot(x,x*4)
plt.legend(['Normal','Fast','Faster'])
plt.show()
#Object Oriented
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,10,1)
y=np.random.randn(len(x))
fig=plt.figure()
ax=fig.add_subplot(111)
l,=plt.plot(x,y)
ax.legend(['ax legend'])
line, =ax.plot(x,y,label='Inline label')
line.set_label('label via method')
plt.show()
坐标轴范围调整
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(1,11,1)
y=x*x
plt.plot(x,y)
plt.axis() # 直接调用会显示一个元组,包含x轴最小最大坐标,y轴最小最大坐标
# 更改坐标轴范围
plt.axis([-5,5,20,60])
# 只调整x轴
plt.xlim([-5,5])
plt.xlim(xmin = -5) # 只调整一边
# 只调整y轴
plt.ylim([-5,5])
plt.ylim(ymax = 5) # 只调整一边
坐标轴刻度调整
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(1,11,1)
plt.plot(x,x)
# 交互式
plt.locator_params('x', nbins = 20)
# Object Oriented
# gca函数获取当前坐标轴
ax = plt.gca()
# 调整坐标轴 nbins代表坐标轴总共有多少格
ax.locator_params('x', nbins = 20) # 指定x轴
日期调整
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import datetime
fig = plt.figure()
start = datetime.datetime(2015,1,1)
stop = datetime.datetime(2016,1,1)
delta = datetime.timedelta(days=1)
dates = mpl.dates.drange(strat, stop, delta)
y = np.random.rand(len(dates))
ax = plt.gca()
ax.plot_date(dates, y, linestyle = '-', marker = '')
date_format = mpl.dates.DataFormatter('%Y-%m-%d') # 设置日期格式
ax.xaxis.set_major_format(date_format) # 将日期格式传入
fig.auto_fmt_xdate() # 让日期位置自适应
添加坐标轴
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(2,20,1)
y1 = x**2
y2 = np.log(x)
# 交互式
plt.plot(x,y1)
# 添加坐标轴twinx添加y坐标轴,twiny添加x坐标轴
plt.twinx()
plt.plot(x,y2,'r') # 在新坐标轴下画图
# Object Oriented
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x,y1)
ax1.set_ylabel('Y1')
ax2 = ax1.twinx()
ax2.plot(x,y2,'r')
ax2.set_ylabel('Y2')
ax1.set_xlabel('compare Y1 and Y2')