背景设置
函数:
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=Figure, clear=False, **kwargs)
num
: integer or string, optional, default: none,num:如果此参数没有提供,则一个新的figure对象将被创建,同时增加figure的计数数值,此数值被保存在figure对象的一个数字属性当中。如果有此参数,且存在对应id的figure对象,则激活对于id的figure对象。如果对应id的figur对象不存在,则创建它并返回它。如果num的值是字符串,则将窗口标题设置为此字符串。figsize
: tuple of integers, optional, default: None
width, height in inches. If not provided, defaults to rc figure.figsize
figsize:以英寸为单位的宽高,缺省值为 rc figure.figsize (1英寸等于2.54厘米)dpi
: integer, optional, default: None dpi:图形分辨率,缺省值为rc figure.dpifacecolor
:
the background color. If not provided, defaults to rc figure.facecolo
facecolor:背景色plt.figure(num="6*2 inches", figsize=(6, 2),facecolor="gray") plt.show()
edgecolor
:
the border color. If not provided, defaults to rc figure.edgecolor
edgecolor:边框颜色clear
: bool, optional, default: False
If True and the figure already exists, then it is cleared
clear:重建figure实例
设置栅格
(1)使用pyplot api命令
matplotlin.pyplot.grid(b, which, axis, color, linestyle, linewidth, **kwargs)
-
b
: 布尔值。就是是否显示网格线的意思。官网说如果b设置为None, 且kwargs长度为0,则切换网格状态。但是没弄明白什 么意思。如果b设置为None,但是又给了其它参数,则默认None值失效。 -
which
: 取值为’major’, ‘minor’, ‘both’。 默认为’major’。看别人说是显示的,我的是Windows7下,用Sublime跑的,minor 只是一个白画板,没有网格,major和both也没看出什么效果,不知道为什么。 -
axis
: 取值为‘both’, ‘x’,‘y’。就是想绘制哪个方向的网格线。不过我在输入参数的时候发现如果输入x或y的时候, 输入的是哪条轴,则会隐藏哪条轴 -
color
: 这就不用多说了,就是设置网格线的颜色。或者直接用c来代替color也可以。 -
linestyle
:也可以用ls来代替linestyle, 设置网格线的风格,是连续实线,虚线或者其它不同的线条。 | ‘-’ | ‘–’ | ‘-.’ | ‘:’ | ‘None’ | ’ ’ | ‘’] -
linewidth
: 设置网格线的宽度
打开栅格:plt.grid(True)
设置栅格格式:plt.grid(color=‘r’, linestyle=’–’, linewidth=1,alpha=0.3)
plt.tick_params(axis="x",labelrotation=-60)
plt.grid(True)
plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
其实就是在设置刻度的基础上,在添加一个列表,来显示刻度。
xticks()返回了两个对象,一个是刻标(locs),另一个是刻度标签
locs, labels = xticks()
如:plt.xticks(['数据'], ["标签"])
# 显示x轴的刻标
xticks( arange(6) )
# 显示x轴的刻标以及对应的标签
xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )
# 导入模块
import matplotlib.pyplot as plt
import numpy as np
# 数据
x = np.linspace(-10, 10, 100)
y = x**2
# 绘图
plt.plot(x, y)
# 设置轴的刻度
plt.xticks(range(-8, 8, 2))
plt.yticks([0, 40, 60], ["bad", 'good', "best"])
# 展示
plt.show()
主副刻度的设置
需要导入:from matplotlib.ticker import MultipleLocator
, FormatStrFormatter
模块
主刻度:(y轴同理)
倍数:ax.xaxis.set_major_locator(MultipleLocator(倍数))
文本格式:ax.xaxis.set_major_formatter(FormatStrFormatter(’%占位数.小数点数f’))
副刻度:(将"major"改为"minor"即可)
倍数:ax.xaxis.set_minor_locator(MultipleLocator(倍数))
文本格式:ax.xaxis.set_minor_formatter(FormatStrFormatter(’%占位数.小数点数f’))
# 导入模块
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import numpy as np
# 数据
x = np.linspace(-30, 30, 100)
y = x**2
# 绘图
plt.plot(x, y)
ax = plt.gca()
# 设置轴的主刻度
# x轴
ax.xaxis.set_major_locator(MultipleLocator(20)) # 设置20倍数
ax.xaxis.set_major_formatter(FormatStrFormatter('%5.1f')) # 设置文本格式
# y轴
ax.yaxis.set_major_locator(MultipleLocator(100)) # 设置100倍数
ax.yaxis.set_major_formatter(FormatStrFormatter('%1.2f')) # 设置文本格式
# 设置轴的副刻度
# x轴
ax.xaxis.set_minor_locator(MultipleLocator(5)) # 设置10倍数
# ax.xaxis.set_minor_formatter(FormatStrFormatter('%2.1f')) # 设置文本格式
# y轴
ax.yaxis.set_minor_locator(MultipleLocator(50)) # 设置50倍数
# ax.yaxis.set_minor_formatter(FormatStrFormatter('%1.0f')) # 设置文本格式
# 设置网格
ax.xaxis.grid(True, which='major') # x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor') # y坐标轴的网格使用次刻度
# 展示
plt.show()
设置轴的数据
以x轴的数为日期,再以plt.gcf().autofmt_xdate()
来旋转显示日期数据。
# 导入模块
import matplotlib.pyplot as plt
import numpy as np
# 数据
N = 4
y = np.random.randint(-20, 20, (1, N)).flatten()
x = ["2019-3-13", "2019-3-14", "2019-3-15", "2019-3-16"]
# 绘图
plt.plot(x, y)
# 旋转日期显示
plt.gcf().autofmt_xdate()
# 展示
plt.show()
全局的设置
在matplotlib目前的绘图文字显示时,是不支持中文的,我们想输出中文,需要设置一下。
matplotlib.rcParams['属性'] = '属性值'
,可以修改全局字体
import matplotlib.pyplot as plt
import matplotlib
# 将全局的字体设置为黑体
matplotlib.rcParams['font.family'] = 'SimHei'
y = [3, 1, 4, 5, 2]
plt.plot(y)
plt.ylabel("纵轴的值")
plt.xlabel("横轴的值")
# 自动保存图片
plt.savefig("test", dpi=600)
plt.show()
2.局部的设置
为了不影响全局的字体,我们可以选择在局部改变字体。
在需要输入中文的地方,输入一下参数
import matplotlib.pyplot as plt
y = [3, 1, 4, 5, 2]
plt.plot(y)
# 改变局部变量
plt.ylabel("纵轴的值", fontproperties="SimHei", fontsize=20)
plt.xlabel("横轴的值", fontproperties="SimHei", fontsize=20, color="green")
plt.savefig("test", dpi=600)
plt.show()
文本显示
带箭头的参数:
s : "string"
xy: 箭头的坐标
xytext: 文字的坐标
arrowprops: 箭头的属性,字典类型
arrowprops=dict(facecolor="red", shrink=0.1, width=2)
facecolor:箭头颜色
shrink:箭头的长度(两坐标距离的比例,0~1)
width:箭头的宽度
import matplotlib.pyplot as plt
y = [3, 1, 4, 5, 2]
plt.plot(y)
# x , y 轴标签
plt.ylabel("纵轴的值", fontproperties="SimHei", fontsize=20)
plt.xlabel("横轴的值", fontproperties="SimHei", fontsize=20, color="green")
# 整体的标签
plt.title(r"整体的标签 $x^{2y +3}$", fontproperties="SimHei", fontsize=30)
# 显示网格
plt.grid(True)
# 再坐标为(1,3)处输出文字
plt.text(1, 3, r"$\mu=100$")
# 有箭头的文字
plt.annotate(r"$\sum_1^nx$", xy=(3, 3), xytext=(3, 4.5),
arrowprops=dict(facecolor="red", shrink=0.1, width=2))
# 设置坐标轴 x(0, 4) y(0, 6)
plt.axis([0, 4, 0, 6])
plt.show()
- annotate:添加注释
- text:添加注释
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)
# 移动坐标
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
# 添加注释 annotate
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
# 添加注释 text
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
图形内的添加文本 plt.text()
plt.figtext()
'''
第一种方式 text()
text(x,y,s,fontdict=None, withdash=False)
参数说明:(1)x,y 坐标位置
(2) 显示的文本
'''
x = np.arange(0,2*np.pi,0.01)
plt.plot(np.sin(x))
'''x,y 代表着坐标系中数值'''
plt.text(20,0,'sin(0) = 0')
'''
第二种方式 figtext()
使用figtext时候,x,y代表相对值,图片的宽度
'''
x2 = np.arange(0,2*np.pi,0.01)
plt.plot(np.cos(x2))
''''''
plt.figtext(0.5,0.5,'cos(0)=0')
plt.show()
添加注释和箭头 plt.annotate()
'''
添加注释 annotate()
参数 :(1)x : 注释文本
(2)xy:
(3) xytext:
(4) 设置箭头,arrowprops
arrowprops : 是一个dict (字典)
第一种方式:{'width':宽度,'headwidth':箭头宽,'headlength':箭头长,
'shrink':两端收缩总长度分数}
例如:arrowprops={'width':5,'headwidth':10,'headlength':10,'shrink':0.1}
第二种方式:'arrowstyle':样式
例如:
有关arrowstyle的样式:'-' 、'->'、'<-'、'-['、'|-|'、'-|>'、'<|-'、'<->'
'fancy','simple','wedge'
'''
x = np.random.randint(0,30,size=10)
x[5] = 30 # 把索引为5的位置改为30
plt.figure(figsize=(12,6))
plt.plot(x)
plt.ylim([-2,35]) # 设置y轴的刻度
plt.annotate(s='this point is important',xy=(5,30),xytext=(7,31),
arrowprops={'arrowstyle':'->'})
plt.show()