折线图(line chart)是我们日常工作、学习中经常使用的一种图表,它可以直观的反映数据的变化趋势。与绘制柱状图、饼状图等图形不同,Matplotlib 并没有直接提供绘制折线图的函数,因此本节着重讲解如何绘制一幅折线图。
绘制单条折线
下面示例是关于 C语言中文网用户活跃度的折线图:
- import matplotlib.pyplot as plt
- x = ["Mon", "Tues", "Wed", "Thur", "Fri","Sat","Sun"]
- y = [20, 40, 35, 55, 42, 80, 50]
- plt.plot(x, y, "g", marker='D', markersize=5, label="周活")
- plt.xlabel("登录时间")
- plt.ylabel("用户活跃度")
- plt.title("C语言中文网活跃度")
- plt.legend(loc="lower right")
- for x1, y1 in zip(x, y):
- plt.text(x1, y1, str(y1), ha='center', va='bottom', fontsize=10)
- plt.savefig("1.jpg")
- plt.show()
|
显示结果如下:

图1:Matplotlib饼状图
绘制多条折线图
当学习完如何绘制单条折线的绘制后,再绘制多条折线也变的容易,只要准备好绘制多条折线图的数据即可。
下面是一个简单示例,绘制了两天内同一时刻,天气温度随时间变化的折线图:
- import matplotlib.pyplot as plt
- x = [5, 8, 12, 14, 16, 18, 20]
- y1 = [18, 21, 29, 31, 26, 24, 20]
- y2 = [15, 18, 24, 30, 31, 25, 24]
- plt.plot(x, y1, 'r',marker='*', markersize=10)
- plt.plot(x, y2, 'b', marker='*',markersize=10)
- plt.title('温度对比折线图')
- plt.xlabel('时间(h)')
- plt.ylabel('温度(℃)')
- for a, b in zip(x, y1):
- plt.text(a, b, b, ha='center', va='bottom', fontsize=10)
- for a, b in zip(x, y2):
- plt.text(a, b, b, ha='center', va='bottom', fontsize=10)
-
- plt.legend(['第一天', '第二天'])
- plt.show()
|
显示结果如下:
 |