python进阶—matplotlib教程

简介:matplotlib是python著名的绘图库,它提供了一整套和matlab相似的API,十分适合交互式进行制图。作为一套面向对象的会图库,它所绘画的图表中的每个绘图元素,都会在内存中有一个对象与之对应,我们只需要调用pyplot绘图模块就能快速实现绘图和设置图表的各种细节。

1、简单绘制(折线图)

import matplotlib.pyplot as plt
import numpy as np

# 图例、标题、标签
x = [1, 2, 3]
y = [5, 7, 4]
x2 = [1, 2, 3]
y2 = [10, 14, 12]
# 生成线条,设置线条名称
plt.plot(x, y, label="First Line")
plt.plot(x2, y2, label="Second Line")
# 给x,y轴创建标签
plt.xlabel("Plot Number")
plt.ylabel("Important Var")
# 设置图的标题
plt.title("Interesting Graph it out")
# 生成默认图例
plt.legend()
plt.show()

2、绘制条形图

plt.bar([1, 3, 5, 7, 9], [5, 2, 7, 8, 2], label="Example one")
# 创建条形图,并设置条形图颜色
plt.bar([2, 4, 6, 8, 10], [8, 6, 2, 5, 6], label="Example Two", color="r")
# 给x,y轴设置标签
plt.xlabel("bar number")
plt.ylabel("bar height")
# 设置图的标题
plt.title("Epic Graph Line")
# 生成默认图例
plt.legend()
plt.show()

3、绘制直方图

# 创建直方图
ages = [22, 55, 62, 45, 21, 22, 34, 42, 42, 4, 99, 102, 110, 120, 121, 122, 130, 111, 115, 112, 80, 75, 65, 54, 44, 43,
        42, 48]
bins = np.linspace(0, 130, 14)
# histtype="bar":绘制条形图,rwidth:设置条形图的宽度
plt.hist(ages, bins, histtype="bar", rwidth=0.8)
plt.xlabel("x")
plt.ylabel("y")
plt.title("Interesting Graph")
plt.legend()
plt.show()

4、绘制散点图

# 散点图
x = np.arange(1, 8, 1)
y = np.array([5, 2, 4, 2, 1, 4, 5])
# color:颜色,s图案大小,market:图案类型
plt.scatter(x, y, label="skitscat", color="k", s=25, marker="o")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.title("Interest Graph")
plt.show()

5、绘制堆叠图

# 堆叠图
days = [1, 2, 3, 4, 5]
sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]
# 为了显示图例,创建每个图例的样式
plt.plot([], [], label="sleeping", color="m", linewidth=5)
plt.plot([], [], label="eating", color="c", linewidth=5)
plt.plot([], [], label="working", color="r", linewidth=5)
plt.plot([], [], label="playing", color="k", linewidth=5)
plt.stackplot(days, sleeping, eating, working, playing, colors=["m", "c", "r", "k"])
plt.xlabel("x")
plt.ylabel("y")
plt.title("Interesting Graph")
plt.legend()
plt.show()

6、绘制饼图

# 创建饼图
slices = [7, 2, 2, 13]
activities = ["sleeping", "eating", "working", "playing"]
cols = ["c", "m", "r", "b"]
# slices:切片数据,labels:标签,colors:颜色,startangle:绘画起始角度,shadow:添加阴影,explode:拉出一个切片,autopct:把百分比放在图表上
plt.pie(slices, labels=activities, colors=cols, startangle=90, shadow=True, explode=(0, 0.1, 0, 0), autopct="%1.1f%%")
plt.title("Interesting Graph")
plt.show()

7、绘制

猜你喜欢

转载自blog.csdn.net/qq_35511580/article/details/81290372