例子
import matplotlib.pyplot as plt
#创建画布
plt.figure(figsize=(20, 8), dpi=100)
#绘制图像
x = [1, 2, 3]
y = [4, 5, 6]
plt.plot(x, y)
#显示图像
plt.show()
具体步骤
import matplotlib.pyplot as plt
import random
# 设置字体
plt.rcParams['font.sans-serif']=['SimHei']
#创建画布
plt.figure()
#绘制图像
x = [1, 2, 3, 4, 5, 6]
y = [2, 5, 3, 4, 5, 9]
plt.plot(x, y)
#显示图像
plt.show()
Matplotlib结构
如何查看api
help(plt.figure)
Help on function figure in module matplotlib.pyplot:
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)
Create a new figure, or activate an existing figure.
Parameters
----------
num : int or str or `.Figure`, optional
A unique identifier for the figure.
If a figure with that identifier already exists, this figure is made
active and returned. An integer refers to the ``Figure.number``
attribute, a string refers to the figure label.
If there is no figure with the identifier or *num* is not given, a new
figure is created, made active and returned. If *num* is an int, it
will be used for the ``Figure.number`` attribute, otherwise, an
auto-generated integer value is used (starting at 1 and incremented
for each new figure). If *num* is a string, the figure label and the
window title is set to this value.
figsize : (float, float), default: :rc:`figure.figsize`
Width, height in inches.
dpi : float, default: :rc:`figure.dpi`
The resolution of the figure in dots-per-inch.
facecolor : color, default: :rc:`figure.facecolor`
The background color.
edgecolor : color, default: :rc:`figure.edgecolor`
The border color.
frameon : bool, default: True
If False, suppress drawing the figure frame.
FigureClass : subclass of `~matplotlib.figure.Figure`
Optionally use a custom `.Figure` instance.
clear : bool, default: False
If True and the figure already exists, then it is cleared.
tight_layout : bool or dict, default: :rc:`figure.autolayout`
If ``False`` use *subplotpars*. If ``True`` adjust subplot
parameters using `.tight_layout` with default padding.
When providing a dict containing the keys ``pad``, ``w_pad``,
``h_pad``, and ``rect``, the default `.tight_layout` paddings
will be overridden.
constrained_layout : bool, default: :rc:`figure.constrained_layout.use`
If ``True`` use constrained layout to adjust positioning of plot
elements. Like ``tight_layout``, but designed to be more
flexible. See
:doc:`/tutorials/intermediate/constrainedlayout_guide`
for examples. (Note: does not work with `add_subplot` or
`~.pyplot.subplot2grid`.)
**kwargs : optional
See `~.matplotlib.figure.Figure` for other possible arguments.
Returns
-------
`~matplotlib.figure.Figure`
The `.Figure` instance returned will also be passed to
new_figure_manager in the backends, which allows to hook custom
`.Figure` classes into the pyplot interface. Additional kwargs will be
passed to the `.Figure` init function.
Notes
-----
If you are creating many figures, make sure you explicitly call
`.pyplot.close` on the figures you are not using, because this will
enable pyplot to properly clean up the memory.
`~matplotlib.rcParams` defines the default values, which can be modified
in the matplotlibrc file.
设置画布的两个重要属性与保存图片
plt.figure(figsize=(20, 8), dpi=100)
# 从4的api可以看出一个是设置图片的宽高,一个是像素点的密集程度
x = [1, 2, 3, 4, 5, 6]
y = [3, 1, 4, 2, 5, 3]
plt.plot(x, y)
# 使用plt.show()会释放掉图片资源因此保存要在显示之前
plt.savefig("./img/test.png")
# 显示图像
plt.show()
案例:显示温度变化状况
raw
# 0.生成数据
x = range(60)
y = [random.uniform(10, 15) for i in x]
# 1.生成画布
plt.figure(figsize=(20, 8), dpi=100)
# 2.图形绘制
plt.plot(x, y)
# 2.1添加x轴刻度
# 3.图像展示
plt.show()
添加自定义x, y刻度
添加下面的代码
构造x, y轴刻度标签
x_ticks_label = [“11点{}分”.format(i) for i in x]
y_ticks = range(40)
plt.xticks(x[::5], x_ticks_label[::5])
plt.yticks(y_ticks[::5])
# 0.生成数据
x = range(60)
y = [random.uniform(10, 15) for i in x]
# 1.生成画布
plt.figure(figsize=(20, 8), dpi=100)
# 2.图形绘制
plt.plot(x, y)
# 2.1添加x, y轴刻度
x_ticks_label = ["11点{}分".format(i) for i in x]
y_ticks = range(40)
plt.xticks(x[::5], x_ticks_label[::5])
# plt.xticks(x_ticks_label[::5]) 会报错,必须先传入数字
plt.yticks(y_ticks[::5])
# 3.图像展示
plt.show()
添加网格和描述
# 0.生成数据
x = range(60)
y = [random.uniform(10, 15) for i in x]
# 1.生成画布
plt.figure(figsize=(20, 8), dpi=100)
# 2.图形绘制
plt.plot(x, y)
# 2.1添加x, y轴刻度
x_ticks_label = ["11点{}分".format(i) for i in x]
y_ticks = range(40)
plt.xticks(x[::5], x_ticks_label[::5])
# plt.xticks(x_ticks_label[::5]) 会报错,必须先传入数字
plt.yticks(y_ticks[::5])
# 2.2添加网格
plt.grid(True, linestyle="--", alpha=0.5)
# 2.3添加描述
plt.xlabel("时间", fontsize=15)
plt.ylabel("温度", fontsize=15)
plt.title("一小时温度变化图", fontsize=20)
# 3.图像展示
plt.show()
案例总结
多次plot及图像风格设置
代码
# 0.生成数据
x = range(60)
# 两条线
y_beijing = [random.uniform(10, 15) for i in x]
y_shanghai = [random.uniform(15, 20) for i in x]
# 1.生成画布
plt.figure(figsize=(20, 8), dpi=100)
# 2.图形绘制
# 先绘北京,lable是用来显示图例的, 后面的color和linestyle设置风格
plt.plot(x, y_beijing, label="北京", color="g", linestyle="-.")
# 再绘上海
plt.plot(x, y_shanghai, label="上海")
# 2.1添加x, y轴刻度
x_ticks_label = ["11点{}分".format(i) for i in x]
y_ticks = range(40)
plt.xticks(x[::5], x_ticks_label[::5])
# plt.xticks(x_ticks_label[::5]) 会报错,必须先传入数字
plt.yticks(y_ticks[::5])
# 2.2添加网格
plt.grid(True, linestyle="--", alpha=0.5)
# 2.3添加描述
plt.xlabel("时间", fontsize=15)
plt.ylabel("温度", fontsize=15)
plt.title("一小时温度变化图", fontsize=20)
# 2.4显示图例
plt.legend()
# 3.图像展示
plt.show()
风格属性列举
多个坐标系显示
import matplotlib.pyplot as plt
import random
# 设置字体
plt.rcParams['font.sans-serif']=['SimHei']
# 0.生成数据
x = range(60)
# 两条线
y_beijing = [random.uniform(10, 15) for i in x]
y_shanghai = [random.uniform(15, 20) for i in x]
# # 1.生成画布
# plt.figure(figsize=(20, 8), dpi=100)
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8), dpi=100)
# # 2.图形绘制
# # 先绘北京,lable是用来显示图例的, 后面的color和linestyle设置风格
# plt.plot(x, y_beijing, label="北京", color="g", linestyle="-.")
# # 再绘上海
# plt.plot(x, y_shanghai, label="上海")
# 第一个坐标系
axes[0].plot(x, y_beijing, label="北京", color="g", linestyle=":")
# 第二个坐标系
axes[1].plot(x, y_shanghai, label="上海")
# # 2.1添加x, y轴刻度
# x_ticks_label = ["11点{}分".format(i) for i in x]
# y_ticks = range(40)
# plt.xticks(x[::5], x_ticks_label[::5])
# # plt.xticks(x_ticks_label[::5]) 会报错,必须先传入数字
# plt.yticks(y_ticks[::5])
# 第一个坐标系
axes[0].set_xticks(x[::5])
axes[0].set_yticks(y_ticks[::5])
axes[0].set_xticklabels(x_ticks_label[::5])
# 第二个坐标系
axes[1].set_xticks(x[::5])
axes[1].set_yticks(y_ticks[::5])
axes[1].set_xticklabels(x_ticks_label[::5])
# # 2.2添加网格
# plt.grid(True, linestyle="--", alpha=0.5)
axes[0].grid(True, linestyle="--", alpha=0.5)
axes[1].grid(True, linestyle="--", alpha=0.5)
# # 2.3添加描述
# plt.xlabel("时间", fontsize=15)
# plt.ylabel("温度", fontsize=15)
# plt.title("一小时温度变化图", fontsize=20)
axes[0].set_xlabel("时间", fontsize=15)
axes[0].set_ylabel("温度", fontsize=15)
axes[0].set_title("北京一小时温度变化图", fontsize=20)
axes[1].set_xlabel("时间", fontsize=15)
axes[1].set_ylabel("温度", fontsize=15)
axes[1].set_title("上海一小时温度变化图", fontsize=20)
# 2.4显示图例
plt.legend()
axes[0].legend()
axes[1].legend()
# 3.图像展示
plt.show()
plot画图拓展
绘制“曲线”图像(细分点)
import matplotlib.pyplot as plt
import random
import numpy as np
# 设置字体
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
# 0. 准备数据
x = np.linspace(-10, 10, 1000) # 在-10到10之间均匀生成1000个数据
# y = np.sin(x)
y = x*x*x
# 1. 创建画布
plt.figure(figsize=(20, 8), dpi=100)
# 2. 绘制函数图像
plt.plot(x, y)
# 2.1 创建网格显示
plt.grid()
# 3. 显示图像
plt.show()
常见图形绘制
散点图
import matplotlib.pyplot as plt
import random
# 设置字体
plt.rcParams['font.sans-serif']=['SimHei']
# 0.生成数据
x = [1, 4, 6, 18, 3, 17, 25, 12]
y = [2, 8, 10, 15, 4, 20, 30, 15]
# 1. 生成画布
plt.figure(figsize=(20, 8), dpi=100)
# 2. 绘制图形
plt.scatter(x, y)
# 3.显示图形
plt.show()
柱状图
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
plt.rcParams['axes.unicode_minus']=False # 正常显示负号
size = 5
# 类似于range()
x = np.arange(size)
month_name = ["{}月".format(i + 1) for i in x]
# 生成三个柱状图的高度
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
total_width, n= 0.3, 3
width = total_width / n
plt.figure(figsize=(20, 8), dpi=100)
plt.bar(x - width, a, width=width, label="a")
plt.bar(x, b, width=width, label="b")
plt.bar(x + width, c, width=width, label="c")
plt.xticks(x, month_name)
plt.grid()
plt.legend()
plt.show()
直方图
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
plt.rcParams['axes.unicode_minus']=False # 正常显示负号
data = np.random.randn(10000)
# 生成画布
plt.figure(figsize=(20, 8), dpi=100)
# 画图
plt.hist(data, bins=40, density=1)
# 显示横轴标签
plt.xlabel("区间")
# 显示纵轴标签
plt.ylabel("频率")
# 显示图标题
plt.title("频率分布直方图")
plt.show()
饼图
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] # 用黑体显示中文
plt.rcParams['axes.unicode_minus']=False # 正常显示负号
labels = ['娱乐','育儿','饮食','房贷','交通','其它']
sizes = [2,5,12,70,2,9]
explode = (0,0,0,0.1,0,0)
plt.figure(figsize=(20, 8), dpi=100)
plt.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',startangle=150)
plt.title("饼图示例-8月份家庭支出")
plt.show()
# 参数详解
# def pie(x, explode=None, labels=None, colors=None, autopct=None,
# pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
# radius=None, counterclock=True, wedgeprops=None, textprops=None,
# center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None)
# x :(每一块)的比例,如果sum(x) > 1会使用sum(x)归一化;
# labels :(每一块)饼图外侧显示的说明文字;
# explode :(每一块)离开中心距离;
# startangle :起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起;
# shadow :在饼图下面画一个阴影。默认值:False,即不画阴影;
# labeldistance :label标记的绘制位置,相对于半径的比例,默认值为1.1, 如<1则绘制在饼图内侧;
# autopct :控制饼图内百分比设置,可以使用format字符串或者format function
# '%1.1f'指小数点前后位数(没有用空格补齐);
# pctdistance :类似于labeldistance,指定autopct的位置刻度,默认值为0.6;
# radius :控制饼图半径,默认值为1;
# counterclock :指定指针方向;布尔值,可选参数,默认为:True,即逆时针。将值改为False即可改为顺时针。
# wedgeprops :字典类型,可选参数,默认值:None。参数字典传递给wedge对象用来画一个饼图。例如:wedgeprops={'linewidth':3}设置wedge线宽为3。
# textprops :设置标签(labels)和比例文字的格式;字典类型,可选参数,默认值为:None。传递给text对象的字典参数。
# center :浮点类型的列表,可选参数,默认值:(0,0)。图标中心位置。
# frame :布尔类型,可选参数,默认值:False。如果是true,绘制带有表的轴框架。
# rotatelabels :布尔类型,可选参数,默认为:False。如果为True,旋转每个label到指定的角度。