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=False
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
plt.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$'])
# 格式化转义 字符串首尾 r'$...$' (matplotlib中)
# xticks(loc, labels): labels 格式化转义方法 r'$-\frac{\pi}{2}$' 留意分数的表示方式
# pi需要转义才能显示为字符 pai. 若$-pi$ 则直接显示-pi
# 如果没有第二个[]参数,刻度值显示如-3.142, -1.571...等浮点数,而不是-pi
plt.yticks([-1, -0.5, 0.5, 1]) # == ax.set_yticks([-1, -0.5, 0.5, 1])
# 方法2:设置坐标轴刻度
# ax.set_yticks([-1, -0.5, 0.5, 1] # 等价于 plt.yticks([-1, -0.5, 0.5, 1])
# ax.set_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 = plt.gca()
# 方法3:坐标刻度定位器 axis :ax.x[y]axis.set_major[minor]_locator(locator)
# 与(plt.xticks , plt.yticks)和 (ax.set_xticks和ax.set_yticks)一样功能
# ax.yaxis.set_major_locator(plt.MaxNLocator(nbins=5, steps=[1, 3, 5, 7, 9])) # 面元划分 4段数据
# ax.yaxis.set_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(offset=0.5, base=1.5)', # 面元宽度(间隔)1.5,从0.5开始
'plt.MultipleLocator()', # 可以自由自定刻度间隔
'plt.LinearLocator(numticks=21)', # 线性划分20等分,21个刻度
'plt.LogLocator(base=2, subs=[1.0])'] # 对数定位器
'''
# 设置坐标轴的刻度参数
plt.tick_params(labelsize=10) # NOTE: 不是fontsize, 是labelsize
# ************************ 坐标轴刻度:end *****************************
# 移动坐标轴:设置零点在坐标轴的位置 ,set_position(tuple) 元素为tuple
ax.spines['left'].set_position(('data',0)) # data 表示position是相对于数据坐标系
ax.yaxis.set_ticks_position('left') # y轴'right': 刻度值显示在right坐标轴上
ax.spines['bottom'].set_position(('data',0))
ax.xaxis.set_ticks_position('bottom') # x轴top:ticks值显示在top坐标轴上
# 隐藏top和right边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_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: False
plt.legend(loc='upper left',shadow=False, fontsize=12)
# 网格 grid参数
plt.grid(color = 'y', linestyle=':', linewidth=1)
# 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 = 'offset points' 相对于目标点
textcoords = 'offset points', # 相对于目标点为原点的坐标系偏移
fontsize = 14,
arrowprops = dict(arrowstyle='->', # 箭头样式, '-|>' '->'
connectionstyle='arc3, rad=.2') # 箭头属性
)
# plt.text: Add text to the axes.
# Add the text s to the axes at location x, y in data coordinates
plt.text(-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、格式化转义书写格式:
mp.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$'])
# 格式化转义 字符串首尾 r'$...$') (matplotlib中)
# xticks(loc, labels): labels 格式化转义方法 r'$-\frac{\pi}{2}$'
# pi需要转义才能显示为字符 pai. 若$-pi$ 则直接显示-pi
# 如果没有第二个[]参数,刻度值显示如-3.142, -1.571...等浮点数,而不是-pi
2、刻度定位器与格式(Tick Locator)
参考链接:matplotlib命令与格式:tick坐标轴主副刻度设置
定义主刻度变量
xmajorLocator = MultipleLocator(20) #将x主刻度标签设置为20的倍数
xmajorFormatter = FormatStrFormatter('%5.1f') #设置x轴标签文本的格式
ymajorLocator = MultipleLocator(0.5) #将y轴主刻度标签设置为0.5的倍数
ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签文本的格式
设置主刻度标签的位置,标签文本的格式
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_major_formatter(xmajorFormatter)
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)
修改次刻度
xminorLocator = MultipleLocator(5) #将x轴次刻度标签设置为5的倍数
yminorLocator = MultipleLocator(0.1) #将此y轴次刻度标签设置为0.1的倍数
设置次刻度标签的位置,没有标签文本格式
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_minor_locator(yminorLocator)
删除坐标轴的刻度显示
ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_formatter(plt.NullFormatter())
涉及日期格式的locator简述
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday=md.MO))
ax.xaxis.set_minor_locator(md.DayLocator())
ax.xaxis.set_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 seconds since the epoch. Use 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:mod:dateutil.rrule
, which have been imported into the :mod:matplotlib.dates
namespace.
class WeekdayLocator(RRuleLocator):
"""
Make ticks on occurrences of each weekday.
"""
def __init__(self, byweekday=1, interval=1, tz=None):
"""
Mark every weekday in *byweekday*; *byweekday* can be a number or
sequence.
Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,
SU, the constants from :mod:`dateutil.rrule`, which have been
imported into the :mod:`matplotlib.dates` namespace.
*interval* specifies the number of weeks to skip. For example,
``interval=2`` plots every second week.
"""
NOTE3:
bymonthday can be an int
or sequence
. Default bymonthday=range(1,32)
class DayLocator(RRuleLocator):
"""
Make ticks on occurrences of each day of the month. For example,
1, 15, 30.
"""
def __init__(self, bymonthday=None, interval=1, tz=None):
"""
Mark every day in *bymonthday*; *bymonthday* can be an int or
sequence.
Default is to tick every day of the month: ``bymonthday=range(1,32)``
"""
locator属性类型:
'''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(offset=0.5, base=1.5)', # 面元宽度(间隔)1.5,从0.5开始
'plt.MultipleLocator()', # 可以自由自定刻度间隔
'plt.LinearLocator(numticks=21)', # 线性划分20等分,21个刻度
'plt.LogLocator(base=2, subs=[1.0])'] # 对数定位器
'''