matplotlib之pyplot模块——获取/设置对象属性值(setp()、getp/get())
當前有效matplotlib版本為:3.4.1。
概述
pyplot模塊提供了獲取/設置對象屬性值的接口。功能類似于Python內置函數getattr和setattr。從源碼上來看,get()是getp()的別名,兩者是等價的。setp()、getp()的底層實現是基于Python內置函數getattr和setattr。
getp()函數:獲取對象屬性
getp()函數的簽名為matplotlib.pyplot.getp(obj, *args, **kwargs)。
常用參數為:
- obj :需要查詢屬性的對象。類型為 Artist對象,即matplotlib所有可見對象。必備參數。
- property:需要查詢的屬性。類型為字符串或None, 默認值為 None。
- 當值為None時,返回對象的所有屬性。
- 當值為某屬性名時,則會返回obj.get_屬性名()的值。
返回值為查詢對象的某個屬性或為None,此時打印輸出全部屬性。
案例:演示getp()函數
import matplotlib.pyplot as plt# 獲得Line2D對象line line,=plt.plot([2,1]) # 獲取line的color屬性值 # 通過Python內置函數getattr和_color屬性獲取 c1=getattr(line,"_color") # 通過Python內置函數getattr和get_color方法獲取 c2=getattr(line,"get_color")() # 通過getp函數獲取 c3=plt.getp(line,"color") print(c1,c2,c3) # 輸出line對象的所有屬性 plt.getp(line)plt.show()控制臺輸出為:
# color屬性值 #1f77b4 #1f77b4 #1f77b4 # line對象所有屬性列表agg_filter = Nonealpha = Noneanimated = Falseantialiased or aa = Truechildren = []clip_box = TransformedBbox( Bbox(x0=0.0, y0=0.0, x1=1.0, ...clip_on = Trueclip_path = Nonecolor or c = #1f77b4 ......setp()函數:設置對象屬性或屬性的取值要求
setp()函數的簽名為matplotlib.pyplot.setp(obj, *args, **kwargs)。
常用參數為:
- obj :需要設置屬性的對象或對象列表。類型為 Artist對象或 Artist對象列表,即matplotlib所有可見對象。必備參數。
- file :當查詢屬性取值要求時輸出文件的位置。類文件對象。默認值為 sys.stdout。
- *args、**kwargs:需要設置的屬性值。
setp()函數的調用方式有很多種:
-
設置一個對象的一個屬性。
line, = plot([1, 2, 3]) setp(line, linestyle='--') -
設置多個對象的一個屬性。
lines = plot([1, 2, 3],[1, 2, 3],[4, 5, 6],[4, 5, 6]) setp(lines, linestyle='--') -
設置一個對象的多個個屬性。
setp(line, linewidth=2, color='r') -
輸出該屬性的取值要求。
setp(line, 'linestyle')
輸出為: linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} -
輸出所有可設置的屬性及其取值要求。
setp(line)
輸出為:
agg_filter: a filter function, ... -
setp 還支持 MATLAB 式的鍵值對。
setp(lines, 'linewidth', 2, 'color', 'r')
案例:演示 setp()函數
import matplotlib.pyplot as pltline,=plt.plot([2,1]) # 利用鍵值對設置屬性 plt.setp(line,color='b') # matlab式鍵值對 plt.setp(line,"color","g") # 利用內置哈數setattr設置屬性值 setattr(line,"_color",'red') # 將color屬性取值要求輸出到標準輸出 plt.setp(line,"color") # 將line對象所有屬性取值要求輸出到標準輸出 plt.setp(line) # 設置多個對象的屬性 lines = plt.plot([1, 2, 3],[1, 2, 3],[4, 5, 6],[4, 5, 6]) plt.setp(lines, linestyle='--') # 將獲取到的color屬性取值要求輸出到setp.log中 with open("setp.log","a+") as f:plt.setp(line,"color",file =f) plt.show()控制臺輸出為:
# color屬性取值要求 color: color # 所有屬性取值要求 agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha: scalar or None animated: bool antialiased or aa: bool clip_box: `.Bbox` clip_on: bool clip_path: Patch or (Path, Transform) or None color or c: color contains: unknown dash_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'} dash_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'} ......總結
在matplotlib當中,所有可見對象都繼承自Artist類,因此,這些對象被稱為Artist。
pyplot模塊的setp()、getp/get()等函數底層其實都是調用的Artist類的相關方法。
屬性操作中屬性名稱可能是一個令人疑惑的地方。
在matplotlib當中,實際的屬性值存儲在_開頭的屬性中,然后對外提供setter 、getter方法調用。
例如Line2D對象,其顏色屬性為_color,對外接口為get_color()、set_color()。通過內置函數dir()即可列出對象的屬性。
源碼
matplotlib.pyplot模塊
def getp(obj, *args, **kwargs):return matplotlib.artist.getp(obj, *args, **kwargs)def get(obj, *args, **kwargs):return matplotlib.artist.get(obj, *args, **kwargs)def setp(obj, *args, **kwargs):return matplotlib.artist.setp(obj, *args, **kwargs)matplotlib.artist模塊
def getp(obj, property=None):if property is None:insp = ArtistInspector(obj)ret = insp.pprint_getters()print('\n'.join(ret))returnreturn getattr(obj, 'get_' + property)()# alias get = getpdef setp(obj, *args, file=None, **kwargs):if isinstance(obj, Artist):objs = [obj]else:objs = list(cbook.flatten(obj))if not objs:returninsp = ArtistInspector(objs[0])if not kwargs and len(args) < 2:if args:print(insp.pprint_setters(prop=args[0]), file=file)else:print('\n'.join(insp.pprint_setters()), file=file)returnif len(args) % 2:raise ValueError('The set args must be string, value pairs')# put args into ordereddict to maintain orderfuncvals = OrderedDict((k, v) for k, v in zip(args[::2], args[1::2]))ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs]return list(cbook.flatten(ret))總結
以上是生活随笔為你收集整理的matplotlib之pyplot模块——获取/设置对象属性值(setp()、getp/get())的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: flexnet服务器运行许可错误,使用试
- 下一篇: frp使用反向代理实现https协议