# Matplotlib 教程 - 折线图

Jinku Hu 2021年3月21日 2019年12月26日 Matplotlib Matplotlib Line Chart

## Matplotlib 绘制直线

``````# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 9, 10)
y = 2 * x
plt.plot(x, y, "b-")
plt.show()
``````

``````plt.plot(x, y, "b-")
``````

## Matplotlib 绘制曲线

``````# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)
y = np.sin(x)

plt.plot(x, y, "r--")

plt.show()
``````

## 线型

``````matplotlib.pyplot.plot(*args, **kwargs)
``````

`x, y` 数据点的水平/垂直坐标
`fmt` 格式字符串，例如’b-‘表示蓝色实线

`**kwargs`

`color``c` 任何 matplotlib 颜色
`figure` `Figure` 实例
`label` 对象
`linestyle``ls` [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) | `'-'`]
`linewidth``lw` 线宽，以 `points` 为单位
`marker` 有效的 `marker` 格式
`markersize``ms` `float` 类型
`xdata` 一维数组
`ydata` 一维数组
`zorder` `float` 类型

### 线的颜色

Matplotlib 中有不同的方法可以在 `color` 参数中命名颜色。

`b` 蓝色
`g` 绿色
`r` 红色
`c` 青色
`m` 品红
`y` 黄色
`k` 黑色
`w` 白色

#### HTML 十六进制字符串

``````color = "#f44265"
``````

#### RGB 元组

``````color = (0.9569, 0.2588, 0.3891)
``````

### 线型

Matplotlib 具有 4 种内置线型，

`-`
`--`
`:`
`:-`
``````# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)

for index, line_style in enumerate(['-', '--', ':', '-.']):
y = np.sin(x - index*np.pi/2)
plt.plot(x, y, 'k', linestyle=line_style, lw=2)

plt.title("Line Style")
plt.grid(True)

plt.show()
``````

### 线宽

``````linewidth = 2 # unit is points
``````

``````lw = 2
``````
``````# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 21)

for line_width in [0.5, 1, 2, 4, 8]:
y = line_width * x
plt.plot(x, y, 'k', linewidth=line_width)

plt.title("Line Width")
plt.grid(True)

plt.show()
``````

Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.