ARTICLE DETAIL

资讯详情

深耕网站SEO优化与搜索引擎排名提升的一线实战洞察。

Python-matplotlib-刻度与格式

Python-matplotlib-刻度与格式 Matplotlib 刻度与格式精确控制坐标轴的刻度位置和标签格式是实现专业图表的必要技能。 Ticker — 刻度定位器Locatorticker模块控制刻度的位置。内置 Locatorimportmatplotlib.pyplotaspltimportmatplotlib.tickerastickerimportnumpyasnp fig,axesplt.subplots(3,2,figsize(12,10))xnp.linspace(0,10,100)locators[(AutoLocator,ticker.AutoLocator()),(MaxNLocator,ticker.MaxNLocator(nbins5)),(LinearLocator,ticker.LinearLocator(numticks10)),(MultipleLocator,ticker.MultipleLocator(base0.5)),(FixedLocator,ticker.FixedLocator([0.5,2,4.7,8.3])),(LogLocator,ticker.LogLocator(base10)),]for(name,loc),axinzip(locators,axes.flat):ax.plot(x,np.sin(x))ax.xaxis.set_major_locator(loc)ax.set_title(name)Locator 完整列表Locator说明常用参数AutoLocator自动选择默认—MaxNLocator最多 N 个刻度nbins,steps,integerLinearLocator等距刻度numticksMultipleLocator基数的倍数位置baseFixedLocator固定位置locs(列表)IndexLocator等距 偏移base,offsetLogLocator对数刻度base,subsSymmetricalLogLocator对称对数base,linthreshNullLocator无刻度—# 常用 Locator 示例ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins6,integerTrue,steps[1,2,5,10]))ax.yaxis.set_major_locator(ticker.MultipleLocator(0.2))# 每 0.2 一个刻度ax.xaxis.set_major_locator(ticker.LogLocator(base10,subsall))# 对数ax.xaxis.set_major_locator(ticker.NullLocator())# 隐藏刻度主刻度与次刻度fig,axplt.subplots(figsize(10,5))ax.plot(x,np.sin(x))# 主刻度major ticksax.xaxis.set_major_locator(ticker.MultipleLocator(2))# 次刻度minor ticksax.xaxis.set_minor_locator(ticker.MultipleLocator(0.5))# 开启次刻度网格ax.grid(whichmajor,colorgray,linestyle-,linewidth0.8)ax.grid(whichminor,colorlightgray,linestyle--,linewidth0.4)# AutoMinorLocator 自动设置次刻度ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(n4))# 每个主刻度间 4 个次刻度 Formatter — 刻度格式化器Formatter控制刻度标签的显示格式。内置 Formatterformatters[(ScalarFormatter,ticker.ScalarFormatter()),(FormatStrFormatter,ticker.FormatStrFormatter(%.2f)),(PercentFormatter,ticker.PercentFormatter(xmax100,decimals1)),(FuncFormatter,ticker.FuncFormatter(lambdax,p:f{x:.1f}°C)),(FixedFormatter,ticker.FixedFormatter([A,B,C,D,E])),(StrMethodFormatter,ticker.StrMethodFormatter({x:.3f})),(EngFormatter,ticker.EngFormatter(unitV)),(LogFormatter,ticker.LogFormatter(base10)),(NullFormatter,ticker.NullFormatter()),]FormatStrFormatter— 格式化字符串ax.yaxis.set_major_formatter(ticker.FormatStrFormatter(%.2f))# 常用格式: %.2f(两位小数), %.0f(整数), %d(整数), %e(科学计数)PercentFormatter— 百分比# xmax100: 0-100 范围显示为 0%-100%# xmax1: 0-1 范围显示为 0%-100%ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax1,decimals0))FuncFormatter— 自定义函数 ⭐# 自定义格式化函数# 接收两个参数: x(刻度值), pos(位置通常不用)defcurrency_fmt(x,pos):ifx1e6:returnf¥{x/1e6:.1f}Melifx1e3:returnf¥{x/1e3:.0f}Kelse:returnf¥{x:.0f}ax.yaxis.set_major_formatter(ticker.FuncFormatter(currency_fmt))# Lambda 版本ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambdax,p:f{x:,.0f}))# 日期格式化fromdatetimeimportdatetime ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambdax,p:datetime.fromtimestamp(x).strftime(%Y-%m)))EngFormatter— 工程计数法ax.yaxis.set_major_formatter(ticker.EngFormatter(unitHz))# 自动使用 k, M, G, m, μ 等单位前缀ScalarFormatter— 偏移量formatterticker.ScalarFormatter()formatter.set_powerlimits((-3,4))# 超出范围才用科学计数法formatter.set_useOffset(True)# 使用偏移量formatter.set_useMathText(True)# LaTeX 风格ax.yaxis.set_major_formatter(formatter) 刻度外观刻度线样式# 刻度线参数ax.tick_params(axisboth,# x, y, bothwhichmajor,# major, minor, bothdirectionin,# in, out, inoutlength8,# 刻度线长度width1.5,# 刻度线宽度colorred,# 刻度线颜色pad8,# 刻度与标签的间距labelsize12,# 标签字体大小labelcolorblack,# 标签颜色labelrotation45,# 标签旋转角度topTrue,# 是否显示顶部刻度rightTrue,# 是否显示右侧刻度bottomTrue,# 是否显示底部刻度leftTrue# 是否显示左侧刻度)# 单独设置ax.tick_params(axisx,labelrotation45,labelsize10)ax.tick_params(axisy,whichminor,length4,colorgray) 轴边框Spinefig,axplt.subplots(figsize(8,5))ax.plot(x,np.sin(x))# 隐藏上方和右侧边框ax.spines[top].set_visible(False)ax.spines[right].set_visible(False)# 移动边框位置ax.spines[left].set_position((data,0))# 左框移到 x0ax.spines[bottom].set_position((data,0))# 下框移到 y0ax.spines[left].set_position((axes,0.05))# 左框在 5% 处ax.spines[left].set_position(center)# 左框在中间# 边框样式ax.spines[bottom].set_color(red)ax.spines[bottom].set_linewidth(2)ax.spines[bottom].set_linestyle(--) 日期刻度格式化importmatplotlib.datesasmdatesfromdatetimeimportdatetime,timedelta# 生成日期数据dates[datetime(2024,1,1)timedelta(daysi)foriinrange(365)]valuesnp.random.randn(365).cumsum()fig,axplt.subplots(figsize(14,5))ax.plot(dates,values)# 日期 Locatorax.xaxis.set_major_locator(mdates.MonthLocator(interval1))# 每月ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekdaymdates.MO))# 每周一# 日期 Formatterax.xaxis.set_major_formatter(mdates.DateFormatter(%Y-%m))ax.xaxis.set_major_formatter(mdates.DateFormatter(%b %d))# Jan 01ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))# 简洁自适应格式推荐# 自动格式化fig.autofmt_xdate(rotation45,haright)# 自动旋转日期标签# 日期 Locator 速查# DayLocator, HourLocator, MinuteLocator, SecondLocator# MonthLocator, YearLocator# WeekdayLocator, AutoDateLocator 实战: 定制坐标轴双格式坐标轴fig,axplt.subplots(figsize(10,6))ax.plot(x,y)# 左侧用原始值ax.yaxis.set_major_formatter(ticker.FormatStrFormatter(%.1f))# 右侧辅助轴用百分比secaxax.secondary_yaxis(right,functions(lambdax:x/y_total*100,# forwardlambdax:x/100*y_total# inverse))secax.yaxis.set_major_formatter(ticker.PercentFormatter())secax.set_ylabel(Percentage)自定义刻度样式Tufte 风格fig,axplt.subplots(figsize(10,5))ax.plot(x,np.sin(x))# 只保留左/下边框forspinein[top,right]:ax.spines[spine].set_visible(False)# 刻度线朝外ax.tick_params(axisboth,directionout,length5,width1)# 网格ax.grid(True,whichmajor,axisy,colorlightgray,linestyle-,linewidth0.5)# 偏移边框ax.spines[left].set_position((outward,10))ax.spines[bottom].set_position((outward,10))[[matplotlib3-总览|← 返回总览]]
返回列表