matplotlib基础1:绘图基本属性设置--xticks(loc,labels)格式化转义标记matplotlib绘图基本属性设置:
定义使其正常显⽰中⽂字体⿊体
⽤来正常显⽰表⽰负号
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 15:11:36 2018
@author: Administrator
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000) # 均匀分布的1000个数 endpoint=Fal
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
# 初始值(x0,y0)
x0 = np.pi * 3 / 4
x1 = -np.pi * 4 / 5
y0_cos = np.cos(x0) / 2
y1_sin = np.sin(x1)
# text内容
text_cont = 'This is a test!'
# 设置图形对象:窗⼝
plt.figure('Figure Object 1', # 图形对象名称窗⼝左上⾓显⽰
figsize = (8, 6), # 窗⼝⼤⼩
dpi = 120, # 分辨率
facecolor = 'lightgray', # 背景⾊
)
# 设置坐标轴边界 xlim ylim
plt.xlim(x.min() * 1.1, x.max() * 1.1)
plt.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
# 设置title
plt.title('Function Curve', fontsize=14)
# ************************ 坐标轴刻度:start *****************************
# ⽅法1:设置刻度值即坐标轴刻度 xticks yticks
np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',
r'$\pi$'])
# 格式化转义字符串⾸尾 r'$...$' (matplotlib中)
# xticks(loc, labels): labels 格式化转义⽅法 r'$-\frac{\pi}{2}$' 留意分数的表⽰⽅式
# pi需要转义才能显⽰为字符 pai. 若$-pi$ 则直接显⽰-pi
# 如果没有第⼆个[]参数,刻度值显⽰如-3.142, -等浮点数,⽽不是-pi
# ⽅法2:设置坐标轴刻度
# ax.t_yticks([-1, -0.5, 0.5, 1] # 等价于 icks([-1, -0.5, 0.5, 1])
# ax.t_yticks([-1, -0.5, 0.5, 1] # 等价于 icks([-1, -0.5, 0.5, 1])
# ax.t_xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi * 3 / 4,
# np.pi],[r'$-\pi$', r'$-\frac{\pi}{2}$',r'$0$',
# r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',#r'$\pi$']) # 显⽰ -3,-2,-1
# 获取当前坐标轴
ax = a()
# ⽅法3:坐标刻度定位器 axis :ax.x[y]axis.t_major[minor]_locator(locator)
# 与(icks , icks)和 (ax.t_xticks和ax.t_yticks)⼀样功能
# ax.yaxis.t_major_locator(plt.MaxNLocator(nbins=5, steps=[1, 3, 5, 7, 9])) # ⾯元划分 4段数据
# ax.yaxis.t_minor_locator(plt.MultipleLocator(0.5)) # 次刻度间隔
'''locator类型:
'plt.NullLocator()',
'plt.MaxNLocator(nbins=5, steps=[1, 3, 5, 7, 9])', # nbin=5:⾯元边界个数即4个buckt steps不知道啥意思 'plt.FixedLocator(locs=[0, 2.5, 5, 7.5, 10])', # 直接指定刻度值位置
'plt.AutoLocator()', # ⾃动分配刻度值位置
'plt.IndexLocator(offt=0.5, ba=1.5)', # ⾯元宽度(间隔)1.5,从0.5开始
'plt.MultipleLocator()', # 可以⾃由⾃定刻度间隔
'plt.LinearLocator(numticks=21)', # 线性划分20等分,21个刻度
'plt.LogLocator(ba=2, subs=[1.0])'] # 对数定位器
'''
# 设置坐标轴的刻度参数
plt.tick_params(labelsize=10) # NOTE: 不是fontsize,是labelsize
# ************************ 坐标轴刻度:end *****************************
# 移动坐标轴:设置零点在坐标轴的位置 ,t_position(tuple) 元素为tuple
ax.spines['left'].t_position(('data',0)) # data 表⽰position是相对于数据坐标系
ax.yaxis.t_ticks_position('left') # y轴'right': 刻度值显⽰在right坐标轴上
ax.spines['bottom'].t_position(('data',0))
ax.xaxis.t_ticks_position('bottom') # x轴top:ticks值显⽰在top坐标轴上
# 隐藏top和right边框
ax.spines['right'].t_color('none')
ax.spines['top'].t_color('none')
plt.plot(x, cos_y,
linestyle='-',
linewidth=2,
color='dodgerblue',
label=r'$y=\frac{1}{2}$cos(x)') # r'$..$'外部不需要引号
plt.plot(x, sin_y,
linestyle='-', # 线型
linewidth=2, # 线宽
color='orangered',
label=r'$y=sin(x)$') # label:legend显⽰的内容
# 设置图例legend, 可以直接设置在plt.plot的label属性中,然后plt.lengend()显⽰
# loc顺序: “先上中下,再左中右” 默认上左, shadow default: Fal
plt.legend(loc='upper left',shadow=Fal, fontsize=12)
# ⽹格 grid参数
# scatter
plt.scatter([x0, x1],[y0_cos, y1_sin], # 两个点的坐标
s = 60, # fontsize
edgecolor='limegreen', # 散点边缘⾊
facecolor='purple', # 散点填充⾊
zorder=3 # Z序,图层顺序
)
# 两点间的线段
# 两点间的线段
plt.plot([x0, x1],[y0_cos, y1_sin],
linestyle='--',
color='limegreen',
alpha=0.4, # 透明度 0~1
marker='o', # 点样式
markersize=6
)
# 对点(x0,y0)备注⽂本
plt.annotate(
r'$\frac{1}{2}cos(\frac{3\pi}{4}) = -\frac{\sqrt{2}}{4}$', # 备注⽂本
xy = (x0, y0_cos), # ⽬标位置
xycoords = 'data', # ⽬标坐标系:相对于数据坐标系
xytext = (-70, -35), # ⽂本位置,偏移量,textcoords = 'offt points' 相对于⽬标点 textcoords = 'offt points', # 相对于⽬标点为原点的坐标系偏移
fontsize = 14,
arrowprops = dict(arrowstyle='->', # 箭头样式, '-|>' '->'
connectionstyle='arc3, rad=.2') # 箭头属性
)
# : Add text to the axes.
# Add the text s to the axes at location x, y in data coordinates
<(-2,
0.5,
'Content:%s' % text_cont, # ⽂本内容 , 可格式化⽅式
fontsize = 10,
ha='center',
va='center',
alpha=0.5,
color = 'r'
)
# 显⽰图像
plt.show()
'''
plot(*args, **kwargs)
Plot y versus x as lines and/or markers.
Call signatures:
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
'''
NOTE: 注意⽤法和格式:
1、格式化转义书写格式:
np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',
r'$\pi$'])
# 格式化转义字符串⾸尾 r'$...$') (matplotlib中)
# xticks(loc, labels): labels 格式化转义⽅法 r'$-\frac{\pi}{2}$'
# pi需要转义才能显⽰为字符 pai. 若$-pi$ 则直接显⽰-pi
# 如果没有第⼆个[]参数,刻度值显⽰如-3.142, -等浮点数,⽽不是-pi
2、刻度定位器与格式(Tick Locator)
参考链接:
定义主刻度变量
xmajorLocator = MultipleLocator(20) #将x主刻度标签设置为20的倍数xmajorFormatter = FormatStrFormatter('%5.1f') #设置x轴标签⽂本的格式ymajorLocator = MultipleLocator(0.5) #将y轴主刻度标签设置为0.5的倍数ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签⽂本的格式
设置主刻度标签的位置,标签⽂本的格式
ax.xaxis.t_major_locator(xmajorLocator)
ax.xaxis.t_major_formatter(xmajorFormatter)
ax.yaxis.t_major_locator(ymajorLocator)
ax.yaxis.t_major_formatter(ymajorFormatter)
修改次刻度
xminorLocator = MultipleLocator(5) #将x轴次刻度标签设置为5的倍数
yminorLocator = MultipleLocator(0.1) #将此y轴次刻度标签设置为0.1的倍数
设置次刻度标签的位置,没有标签⽂本格式
ax.xaxis.t_minor_locator(xminorLocator)
ax.yaxis.t_minor_locator(yminorLocator)
删除坐标轴的刻度显⽰
ax.yaxis.t_major_locator(plt.NullLocator())
ax.xaxis.t_major_formatter(plt.NullFormatter())
涉及⽇期格式的locator简述
ax.xaxis.t_major_locator(md.WeekdayLocator(byweekday=md.MO))
ax.xaxis.t_minor_locator(md.DayLocator())
ax.xaxis.t_major_formatter(md.DateFormatter('%d %b %Y'))
NOTE1:
Python only supports :mod:datetime :func:strftime formatting for years greater than 1900
class DateFormatter(ticker.Formatter):
"""
Tick location is conds since the epoch. U a :func:`strftime`
format string.
Python only supports :mod:`datetime` :func:`strftime` formatting
for years greater than 1900. Thanks to Andrew Dalke, Dalke
Scientific Software who contributed the :func:`strftime` code
below to include dates earlier than this year.
"""
NOTE2:
Elements of byweekday must be one of MO, TU, WE, TH, FR, SA,
SU, the constants from:ule, which have been imported into the :mod:matplotlib.dates namespace.
class WeekdayLocator(RRuleLocator):
"""
Make ticks on occurrences of each weekday.
"""
def __init__(lf, byweekday=1, interval=1, tz=None):
"""
Mark every weekday in *byweekday*; *byweekday* can be a number or
quence.
Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
SU, the constants from :mod:`ule`, which have been
imported into the :mod:`matplotlib.dates` namespace.
*interval* specifies the number of weeks to skip. For example,
``interval=2`` plots every cond week.
"""
NOTE3:
bymonthday can be an int or quence. Default bymonthday=range(1,32)