在数据分析中重要的一种方法是对数据进行对比分析,通常会把相同类型的数据绘制在同一张表格中,比如把昨天的日活和今天的日活绘制在同一张图表中,这样通过图表的对比很容易发现数据的趋势和问题。有时候一个图表跟另一个图表相关性也比较大,在分析这张图表的时候,需要了解另一个图表的趋势,这时候把这些图表放在一起,可以方便分析。
在同一张图表中显示同一种类型数据
在plot
中本身就支持把同样的数据存放在一张表格中,在上一章中已经把大部分图表的属性介绍了一边,在绘制多数据时,这些属性一样可以使用。
下面绘制一天24小时,新增用户数据,用于对比:
import numpy as np
import matplotlib.pyplot as plt
#显示中文配置
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.style.use("ggplot")
plt.title(u"阿猫学编程 - 多图表绘制 - 日活")
t1 = np.arange(0,24)
t2 = np.random.random_integers(-10,10,24)
t2 = t2.cumsum()
t3 = t2 + np.random.random_integers(-8,8,24)
plt.xticks([x for x in range(0,24)])
plt.plot(t1,t2,'-',color = 'coral',label=u"2018-01-01")
plt.plot(t1,t3,'-',color = 'orange',label = '2018-01-02')
plt.legend(loc='upper left')
plt.show()
图表如下:
通过对轴的控制,在一张图上绘制多张表。 axes
设置位置,x,y 和 高度,宽度。axes
以后,绘图就在该区域,这里一个官网代码:
import matplotlib.pyplot as plt
import numpy as np
# create some data to use for the plot
dt = 0.001
t = np.arange(0.0, 10.0, dt)
r = np.exp(-t[:1000]/0.05) # impulse response
x = np.random.randn(len(t))
s = np.convolve(x, r)[:len(x)]*dt # colored noise
# the main axes is subplot(111) by default
plt.plot(t, s)
plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])
plt.xlabel('time (s)')
plt.ylabel('current (nA)')
plt.title('Gaussian colored noise')
# this is an inset axes over the main axes
plt.axes([.65, .6, .2, .2], facecolor='y')
n, bins, patches = plt.hist(s, 400, normed=1)
plt.title('Probability')
plt.xticks([])
plt.yticks([])
# this is another inset axes over the main axes
plt.axes([0.2, 0.6, .2, .2], facecolor='y')
plt.plot(t[:len(r)], r)
plt.title('Impulse response')
plt.xlim(0, 0.2)
plt.xticks([])
plt.yticks([])
plt.show()
绘制结果如下:
平分图表,在上面显示不同表格数据:
subplot
是把一个平面分为几个小平面,subplot
第一个数为总共几行,第二个数为共有几列,第三个数表示第几个图,从左到右,从上到下开始数。
例如:subplot(223)
: 平面分为2*2的小区域,现在要画的为第三副,也就是第二行第一列的那副。
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
# f(t)函数
plt.figure(1)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
#cos函数
plt.subplot(222)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
#平方函数
plt.subplot(223)
plt.plot(t2, t2**2, 'y-.')
#随机数
plt.subplot(224)
plt.plot(t2, np.random.rand(250), 'k+')
plt.show()
得到如下的图片:
这里还有一个函数 figure
表示新建一个平面,默认下为plt.figure(1)
,如果需要再建一个平面为 plt.figure(2)
。