本篇文章介绍 matplotlib 包的基本使用。这会是一个系列文章,之后我会逐步介绍Python更高级的绘图方法。
环境搭建
对于新手来说,最简单的方式就是安装 Anacoda 了,这是它的官方网站https://www.anaconda.com/。
百度百科:
Anaconda指的是一个开源的Python发行版本,其包含了conda、Python等180多个科学包及其依赖项。
使用的Python库
- numpy:NumPy系统是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix))。
- pandans:Pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。
- matplotlib:Python 的绘图库
示例 1:绘制简单正弦函数
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x) # sin 函数
plt.plot(x,y)
plt.show()
linspace 函数解释:
np.linspace(start, stop, num=50)
Parameters
----------
start :
The starting value of the sequence.
stop : scalar
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
Returns
-------
samples : ndarray
示例 2:在图片中加入标签
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 1.1, 0.01)
y = x**2
plt.figure(figsize=(9,9)) # 设置画布大小
plt.title('lines') # 设置title
plt.xlabel('x1') # 设置x轴标签
plt.ylabel('y')
plt.xlim((0, 1)) # 设定x轴的范围
plt.ylim((0, 1))
plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1]) # 设置轴刻度
plt.yticks([0, 0.2, 0.4, 0.6, 0.8, 1])
plt.plot(x,y, label='y = x^2')
plt.legend(loc='best')
plt.show()
arange函数介绍:
np.arange([start,] stop[, step,])
Parameters
----------
start : number, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : number
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : number, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
Returns
-------
samples : ndarray
示例 3: 微信阅读量统计
数据格式:
Date | Counts | Times |
---|---|---|
2017/10/1 | 399 | 763 |
2017/10/2 | 126 | 745 |
import matplotlib.pyplot as plt
import pandas as pd
wechat = pd.read_excel("wechat.xlsx")
wechat.Date = pd.to_datetime(wechat.Date, format='%Y-%m-%d')
plt.plot(wechat.Date,
wechat.Counts,
linestyle='-',
linewidth=2,
color='steelblue',
marker='o', # 折线图中添加圆点
markersize=6,
markeredgecolor='black',
markerfacecolor='red'
)
plt.ylabel('Counts')
plt.xticks(rotation=45) # x 刻度旋转角度
plt.title("Counts Statistic")
plt.show()