matplotlib| 01. 座標軸刻度樣式設置

01. 座標軸刻度樣式設置

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator,MultipleLocator,FuncFormatter

主要使用到的函數

MultipleLocator()

定義主刻度線的間隔

AutoMinorLocator()

定義次刻度的間隔

FuncFormatter()

設置自定義的刻度標籤格式(如小數位數)

FormatStrFormatter()

設置自定義的刻度標籤格式(如小數位數、添加單位符號)

ax.xaxis.set_major_locator()

ax.xaxis.set_minor_locator()

設置主/次座標軸的刻度位置

ax.xaxis.set_major_formatter

ax.xaxis.set_minor_formatter()

設置主/次座標軸的刻度格式(小數位數)

ax.tick_params()

設置主/次座標軸刻度線和刻度標籤樣式(大小、顏色)

ax.xaxis.get_ticklabels()

ax.xaxis.get_ticklines()

獲取主/次座標軸刻度線和刻度標籤對象

x=np.linspace(0.5,3.5,100)
y=np.sin(x)

fig=plt.figure(figsize=(8,8))
ax=fig.add_subplot(1,1,1) # 行 列 序號

# 主刻度線設置
ax.xaxis.set_major_locator(MultipleLocator(1.0))# 在x軸的1倍處設置主刻度線
ax.yaxis.set_major_locator(MultipleLocator(1.0))

# 次刻度線設置
ax.xaxis.set_minor_locator(AutoMinorLocator(4))# 設置次要刻度線的顯示位置,分爲四等分
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# 設置x軸刻度格式,小數位數
def minor_tick(x,pos):
    if not x%1.0:
        return ""
    return "%.2f"%x

ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))

# 設置座標軸樣式和標籤
# y軸刻度及標籤
ax.tick_params("y",which="major",
              length=15,width=2,
              colors="r")
# x軸刻度及標籤
ax.tick_params(which="minor",
              length=5,width=1,
              labelsize=10,labelcolor="0.25")

# 設置x,y軸範圍
ax.set_xlim(0,4)
ax.set_ylim(0,2)

# 繪製圖形
ax.plot(x,y,c=(0.25,0.25,1.00),lw=2,zorder=10) # zorder:設置繪圖層級
# ax.plot(x,y,c=(0.25,0.25,1.00),lw=2,zorder=0)

# 設置格網
ax.grid(linestyle="-",linewidth=0.5,color='r',zorder=0)

plt.show()

fig=plt.figure(facecolor=(1.0,1.0,0.9412))

ax=fig.add_axes([0.1,0.1,0.5,0.5]) # left, bottom, width, height = 0.1, 0.1, 0.8, 0.8

for ticklabel in ax.xaxis.get_ticklabels():
    ticklabel.set_color("slateblue")
    ticklabel.set_fontsize(18)
    ticklabel.set_rotation(30)
    
for tickline in ax.yaxis.get_ticklines():
    tickline.set_color("lightgreen")
    tickline.set_markersize(20)
    tickline.set_markeredgewidth(2)
    
plt.show()

from calendar import month_name,day_name
from matplotlib.ticker import FormatStrFormatter

fig=plt.figure()
ax=fig.add_axes([0.2,0.2,0.7,0.7])

x=np.arange(1,8,1)
y=2*x

ax.plot(x,y,ls="-",color="orange",marker="o",ms=20,mfc="c",mec="c")

ax.yaxis.set_major_formatter(FormatStrFormatter(r"$%1.1f\yen$"))

plt.xticks(x,day_name[0:7],rotation=20)

ax.set_xlim(0,8)
ax.set_ylim(0,18)

plt.show()

 

參考鏈接:

https://matplotlib.org/3.3.3/api/ticker_api.html#matplotlib.ticker.Locator

《Python數據可視化之matplotlib實踐》, 電子工業出版社, 2018-9

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章