master
/ 2Matplotlib 基础.ipynb

2Matplotlib 基础.ipynb @96fc089view markup · raw · history · blame

Notebook

Matplotlib 基础

在这节课中,我们将会学习到 Matplotlib 的相关内容。

通过 Matplotlib,我们可以仅编写几行代码,就生成直方图,折现图,散点图等,高效美观的展示我们的数据。

导入 matplotlibnumpy

In [1]:
import matplotlib.pyplot as plt
from numpy import *
%matplotlib inline

plot 二维图

plt.plot(y)
plt.plot(x, y)
plt.plot(x, y, format_string)

只给定 y 值,默认以下标为 x 轴:

In [2]:
x = linspace(0, 2 * pi, 50)
plt.plot(sin(x));

给定 xy 值:

In [3]:
plt.plot(x, sin(x));

多条数据线:

In [4]:
plt.plot(x, sin(x),
    x, sin(2 * x));

使用字符串,给定线条参数:

In [5]:
plt.plot(x, sin(x), 'r-^');

多线条:

In [6]:
plt.plot(x, sin(x), 'b-o',
    x, sin(2 * x), 'r-^');

编程练习

在同一幅图中绘制 sin(x), sin(2*x), sin(3*x) 三条曲线。颜色分别为蓝色,红色,黄色。

In [ ]:
# 请编写你的答案
In [ ]:
import matplotlib.pyplot as plt
from numpy import *
%matplotlib inline
x = linspace(0, 2 * pi, 50)
plt.plot(x, sin(x), 'b', x, sin(2 * x), 'r', x, sin(3 * x), 'y');

scatter 散点图

scatter(x, y)
scatter(x, y, size)
scatter(x, y, size, color)

假设我们想画二维散点图:

In [8]:
plt.plot(x, sin(x), 'bo');

可以使用 scatter 达到同样的效果:

In [9]:
plt.scatter(x, sin(x));
In [10]:
x = random.rand(200)
y = random.rand(200)
size = random.rand(200) * 30
color = random.rand(200)
plt.scatter(x, y, size, color)
# 显示颜色条
plt.colorbar();

编程练习

要求:使用 scatter 绘制 sin(x)的二维散点图,把颜色设置为红色,散点形式设置为三角形.

In [17]:
# 请编写你的答案
In [ ]:
import matplotlib.pyplot as plt
x = linspace(0, 10, 30)
plt.scatter(x, sin(x), marker='^', color='r');

多图

使用figure()命令产生新的图像:

In [4]:
t = linspace(0, 2*pi, 50)
x = sin(t)
y = cos(t)
plt.figure()
plt.plot(x)
plt.figure()
plt.plot(y);

或者使用 subplot 在一幅图中画多幅子图:

subplot(row, column, index)
In [20]:
plt.subplot(1, 2, 1)
plt.plot(x)
plt.subplot(1, 2, 2)
plt.plot(y);

编程练习

要求:在上下排布的2个子图中,显示sin(x)和cos(x)的图像,请编写代码实现。

In [21]:
# 请编写你的答案
In [ ]:
fig = plt.figure()
plt.subplot(2, 1, 1)
plt.plot(x)
plt.subplot(2, 1, 2)
plt.plot(y);

向图中添加数据

默认多次 plot 会叠加:

In [12]:
plt.plot(x)
plt.plot(y);

标签

可以在 plot 中加入 label ,使用 legend 加上图例:

In [25]:
plt.plot(x, label='sin')
plt.plot(y, label='cos')
plt.legend();

或者直接在 legend中加入:

In [26]:
plt.plot(x)
plt.plot(y)
plt.legend(['sin', 'cos']);

坐标轴,标题,网格

可以设置坐标轴的标签和标题:

In [7]:
x = linspace(0, 2 * pi, 50)
plt.plot(x, sin(x))
plt.xlabel('radians')
# 可以设置字体大小
plt.ylabel('amplitude', fontsize='large')
plt.title('Sin(x)');

用 'grid()' 来显示网格:

In [8]:
plt.plot(x, sin(x))
plt.xlabel('radians')
plt.ylabel('amplitude', fontsize='large')
plt.title('Sin(x)')
plt.grid();

编程练习

要求:绘制 cos(x) 的图,包含坐标轴、标题和网格。

In [21]:
# 请编写你的答案
In [ ]:
plt.plot(x, cos(x))
plt.xlabel('radians')
plt.ylabel('amplitude', fontsize='large')
plt.title('Cos(x)')
plt.grid();

直方图

从高斯分布随机生成1000个点得到的直方图:

In [19]:
plt.hist(np.random.randn(1000));

更多例子请参考下列网站:

http://matplotlib.org/gallery.html

编程练习

要求: 已知某商店出售 3 种水果,当天的营业额分别为苹果:100,香蕉:200,葡萄:250,请绘制饼图,显示三种水果的占比。

In [21]:
# 请编写你的答案
In [ ]:
labels = [u'苹果',u'香蕉',u'葡萄'] #定义标签
sizes = [100,200,300,] #每块值
plt.pie(sizes, labels=labels, autopct = '%3.2f%%');