用matplotlib绘制Line Chart

-- TOC --

所谓Line Chart,就是用直线将二维平面上的点连接起来所形成的数据图形。这是一种很基本的图形,用处广泛!

下面的示例代码,绘制了三条line charts:

import matplotlib.pyplot as plt

x  = (1,3,2,4,5,6,7,8,9)
y1 = (4,3,2,1,6,7,8,9,5)
y2 = (5,4,3,2,1,6,7,8,9)
y3 = (1,9,8,2,3,7,6,4,5)

fig, ax = plt.subplots()

ax.set_title('Line Chart')
ax.set_xlabel('X')
ax.set_ylabel('Y')

ax.plot(x,y1, label='line 1')
ax.plot(x,y2, 'go--', linewidth=0.4, label='line 2')
ax.plot(x,y3, 'rx-.', linewidth=0.7, label='line 3',
                       markersize=16, alpha=0.5)
ax.legend()

plt.show()

效果图:

line_chart

当点足够多时,看起来就是曲线!

下面的示例代码,画出了sin函数在-10到10之间的图形:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10,10,10000)
y1 = np.sin(x)
y2 = np.cos(x)

fig, ax = plt.subplots()
fig.subplots_adjust(top=0.75, bottom=0.25)

ax.set_title('sin & cos')
ax.set_xlabel('X')
ax.set_ylabel('Sin/Cos')

ax.plot(x,y1, 'r', linewidth=0.5, label='sin')
ax.plot(x,y2, 'g', linewidth=0.5, label='cos')
ax.legend()

plt.show()

效果图:

line_chart_sin

画垂直线

有同学在问如何画垂直线,其实就是两个点的x轴一样,y轴不一样而已,请看如下示例:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
fig.subplots_adjust(top=0.8,bottom=0.2)

ax.set_title('Vertical Line')
for i in range(8):
    ax.plot((i,i),(i,i+2))

plt.show()

效果图:

vertical_line

本文链接:https://cs.pynote.net/sf/python/matplotlib/202309231/

-- EOF --

-- MORE --