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])'] # 對數定位器
'''