三、图形样式、Matplotlib高级设置

三、图形样式、Matplotlib高级设置三 图形样式 Matplotlib 高级设置 3 1 图表刻度 指示注解定制化样式 3 1 1 添加图例和标题导入支持库 importmatplo pyplotasplti tickerimport MultipleLoca FuncFormatte 设置中文显示 mpl rcParams font sans serif orientations 1 1 0 1 1 1 1 0

三、图形样式、Matplotlib高级设置

3.1 图表刻度、指示注解定制化样式

3.1.1 添加图例和标题

导入支持库:

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

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

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

调用函数绘制图形,设置标尺:

fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111) ax.xaxis.set_minor_locator(MultipleLocator(1.0)) ax.yaxis.set_minor_locator(MultipleLocator(1.0)) ax.xaxis.set_minor_locator(AutoMinorLocator(4)) ax.yaxis.set_minor_locator(AutoMinorLocator(4)) def minor_tick(x,pos): if not x % 10: return "" return "%.2f" % x ax.tick_params("y",which="major", length=15,width=2.0, colors="r") ax.tick_params(which="minor", length=5,width=1.0, labelsize=10,labelcolor="0.25") 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) ax.grid(linestyle="-",linewidth=0.5, color="r",zorder=0) plt.show() 

运行结果:

img

3.1.2 刻度标签和刻度线样式的定制化

导入支持库:

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

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

调用函数绘制图形,设置标尺:

fig = plt.figure(facecolor=(1.0,1.0,0.9412)) ax = fig.add_axes([0.1,0.4,0.5,0.5]) 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() 

运行结果:

img

3.1.3 刻度标签和刻度线样式的定制化

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from calendar import month_name,day_name from matplotlib.ticker import FormatStrFormatter 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

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

调用函数绘制图形,设置标尺:

fig = plt.figure() ax = fig.add_axes([0.2,0.2,0.7,0.7]) ax.plot(x,y,ls="-",lw=2,color="orange",marker="o",ms=20,mfc="c",mec="c") ax.yaxis.set_major_formatter(FormatStrFormatter(r"$\yen%1.1f$")) plt.xticks(x,day_name[0:7],rotation=20) ax.set_xlim(0,8) ax.set_ylim(0,18) plt.show() 

运行结果:

img

3.1.4 添加有指示注解和无指示注解

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from calendar import month_name,day_name 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

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

调用函数绘制图形,设置标尺:

fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111) ax.plot(x,y,c="b",ls="--",lw=2) ax.annotate("maximum",xy=(np.pi/2,1.0),xycoords="data",xytext=((np.pi/2)+0.15,0.8),textcoords="data", weight="bold",color="r",arrowprops=dict(arrowstyle="->",connectionstyle="arc3",color="r")) ax.text(2.8,0.4,"$y=\sin(x)$",fontsize=20,color="b",bbox=dict(facecolor="y",alpha=0.5)) plt.show() 

运行结果:

img

3.2 水印和趋势线

3.2.1 文本的水印效果

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(0.0,10,40) y = np.random.randn(40) 

调用函数绘制图形,设置标尺:

plt.plot(x,y,ls="-",lw=2,marker="o",ms=20,mfc="orange",alpha=0.6) plt.grid(ls=":",color="gray",alpha=0.5) plt.text(1,2,"Matplotlib",fontsize=50,color="gray",alpha=0.5) plt.show() 

运行结果:

img

3.2.2 有箭头指示的趋势线

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(0.0,10,2000) y = np.sin(x) 

调用函数绘制图形,设置标尺:

fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x,y,ls="-",lw=2) ax.set_ylim(-1.5,1.5) arrowprops = dict(arrowstyle="-|>",color="r") ax.annotate("", (3*np.pi/2,np.sin(3*np.pi/2)+0.05), xytext=(np.pi/2,np.sin(np.pi/2)+0.005), color="r", arrowprops=arrowprops) ax.arrow(0.0,-0.4,np.pi/2,1.2,head_width=0.05,head_length=0.1, fc="g",ec="g") ax.grid(ls=":",color="gray",alpha=0.6) plt.show() 

运行结果:

img

3.2.3 桑葚图

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from matplotlib.sankey import Sankey 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

flows=[0.2,0.1,0.4,0.3,-0.6,-0.05,-0.15,-0.2] 

调用函数绘制图形,设置标尺:

labels=["","","","","family","trip","education","sport"] orientations=[1,1,0,-1,1,-1,1,0] sankey=Sankey() sankey.add(flows=flows, labels=labels, orientations=orientations, color="c", fc="lightgreen", patchlabel="Life Cost", alpha=0.7) diagrams = sankey.finish() diagrams[0].texts[4].set_color("r") diagrams[0].texts[4].set_weight("bold") diagrams[0].text.set_fontsize(20) diagrams[0].text.set_fontweight("bold") plt.title("日常生活的成本开始流量图") plt.show() 

运行结果:

img

3.3 一张画布多个子区的绘图

3.3.1 添加图例和标题

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(-2*np.pi,2*np.pi,200) y = np.sin(x) y1 = np.cos(x) 

调用函数绘制图形,设置标尺:

plt.subplot(121) plt.plot(x,y) plt.subplot(122) plt.plot(x,y1) plt.show() 

运行结果:

img

3.3.2 在非等分画布的绘图区域上实现图形展示
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(0.0,2*np.pi) y = np.cos(x)*np.sin(x) 

调用函数绘制图形,设置标尺:

fig = plt.figure() ax1 = fig.add_subplot(121) ax1.margins(0.03) ax1.plot(x,y,ls="-",lw=2,color="b") ax2 = fig.add_subplot(222) ax2.margins(0.7,0.7) ax2.plot(x,y,ls="-",lw=2,color="r") ax3 = fig.add_subplot(224) ax3.margins(x=0.1,y=0.3) ax3.plot(x,y,ls="-",lw=2,color="g") plt.show() 

运行结果:

img

3.3.3 子区域跨越固定的网格布局
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(0.0,4.0,100) y = np.random.randn(100) y1 = np.sin(x) 

调用函数绘制图形,设置标尺:

plt.subplot2grid((2,3),(0,0),colspan=2) plt.scatter(x,y,c="c") plt.title("散点图") plt.subplot2grid((2,3),(0,2)) plt.title("空白绘图区域") plt.subplot2grid((2,3),(1,0),colspan=3) plt.plot(x,y1,lw=2,ls="-") plt.xlim(0,3) plt.grid(True,ls=":",c="r") plt.title("折线图") plt.suptitle("subplot2grid()函数的实例展示",fontsize=15) plt.show() 

运行结果:

img

3.3.4 一张画布和两个子区的绘图模式
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(0,2*np.pi,500) y = np.sin(x)*np.exp(-x) 

调用函数绘制图形,设置标尺:

font_style = dict(fontsize=18,weight="black") fig,ax = plt.subplots(1,2,sharey=True) ax1 = ax[0] ax1.plot(x,y,"k--",lw=2) ax1.set_title("折线图") ax1.grid(ls=":",lw=1,color="gray",alpha=0.8) ax2 = ax[1] ax2.scatter(x,y,s=10,c="skyblue",marker="o") ax2.set_title("散点图") plt.suptitle("创建一张画布和两个子区域的绘图模式",font_style) plt.show() 

运行结果:

img

3.4 多种统计图形的组合展示和共享单一绘图坐标轴

3.4.1 多种统计图形的组合展示
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置画布分区:

fig,ax = plt.subplots(2,3) 

设置第一个绘图:

colors = ["#8dd3c7","#ffffb3","#bebada"] ax[0,0].bar([1,2,3],[0.6,0.2,0.8],color=colors,width=0.5,hatch="///",align="center") ax[0,0].errorbar([1,2,3],[0.6,0.2,0.8],yerr=0.1,capsize=0,ecolor="#377eb8",fmt="o:") ax[0,0].set_ylim(0,1.0) 

设置第二个绘图:

ax[0,1].errorbar([1,2,3],[20,30,36],xerr=2,color="#4daf4a",elinewidth=2,fmt="s",label="ETN") ax[0,1].legend(loc=3,fancybox=True,shadow=True,fontsize=10,borderaxespad=0.4) ax[0,1].set_ylim(10,40) ax[0,1].set_xlim(-2,6) ax[0,1].grid(ls=":",lw=1,color="gray",alpha=0.5) 

设置第三个绘图:

x3=np.arange(1,10,0.5) y3=np.cos(x3) ax[0,2].stem(x3,y3,basefmt="r-",linefmt="b-",markerfmt="bo",label="lifesignal") ax[0,2].legend(loc=2,fontsize=8,frameon=False,borderpad=0.0,borderaxespad=0.6) ax[0,2].set_xlim(0,11) ax[0,2].set_ylim(-1.1,1.1) 

设置第四个绘图:

x4 = np.linspace(0.2*np.pi,500) x4_1 = np.linspace(0.2*np.pi,1000) y4 = np.cos(x4)*np.exp(-x4) y4_1 = np.sin(2*x4_1) line1,line2 = ax[1,0].plot(x4,y4,"k-",x4_1,y4_1,"r-",lw=2) ax[1,0].legend((line1,line2),("energy","patience"),loc="upper center",fontsize=8,ncol=2,framealpha=0.3,mode="expand",columnspacing=2,borderpad=0.1) ax[1,0].set_ylim(-2,2) ax[1,0].set_xlim(0,2*np.pi) 

设置第五个绘图:

x5 = np.random.rand(100) ax[1,1].boxplot(x5,vert=False,showmeans=True,meanprops=dict(color="g")) ax[1,1].set_yticks([]) ax[1,1].set_xlim(-1.1,1.1) ax[1,1].set_ylabel("Micro SD Card") ax[1,1].text(-1.0,1.2,"net weight",fontsize=20,style="italic",weight="black",family="monospace") 

设置第六个绘图:

mu=0.0 sigma=1.0 x6 = np.random.randn(10000) n,bins,patches=ax[1,2].hist(x6,bins=30,histtype="stepfilled",cumulative=True,density=True,color="cornflowerblue",label="Test") y=((1/(np.sqrt(2*np.pi)*sigma))*np.exp(-0.5*(1/sigma*(bins-mu))2)) y = y.cumsum() y /= y[-1] ax[1,2].plot(bins,y,"r--",linewidth=1.5,label="Theory") ax[1,2].set_ylim(0.0,1.1) ax[1,2].grid(ls=":",lw=1,color="grey",alpha=0.5) ax[1,2].legend(loc="upper left",fontsize=8,shadow=True,fancybox=True,framealpha=0.8) 

显示绘图结果:

plt.subplots_adjust() plt.show() fig 

运行结果:

img

3.4.2 共享单一绘图区域的坐标轴

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置第一个绘图:

fig,ax1=plt.subplots() t = np.arange(0.05,10.0,0.01) s1 = np.exp(t) ax1.plot(t,s1,c="b",ls="-") ax1.set_xlabel("x坐标轴") ax1.set_ylabel("以e为底指数函数",color="b") ax1.tick_params("y",colors="b") 

设置第二个绘图:

#设置x轴公轴 ax2 = ax1.twinx() s2 = np.cos(t2) ax2.plot(t,s2,c="r",ls=":") ax2.set_ylabel("余弦函数",color="r") ax2.tick_params("y",color="r") plt.show() fig 

运行结果

img

3.5 Matplotlib高级设置-坐标轴

3.5.1 添加图例和标题

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

调用函数绘制图形,设置标尺:

plt.axes([0.05,0.7,.3,.3],frameon=True,facecolor="y",aspect="equal") plt.plot(np.arange(3),[0,1,0],color="blue",linewidth=2,linestyle="--") plt.axes([0.3,0.4,.3,.3],frameon=True,facecolor="y",aspect="equal") plt.plot(2+np.arange(3),[0,1,0],color="blue",linewidth=2,linestyle="-") plt.axes([0.55,0.1,.3,.3],frameon=True,facecolor="y",aspect="equal") plt.plot(4+np.arange(3),[0,1,0],color="blue",linewidth=2,linestyle=":") plt.show() 

运行结果:

img

3.5.2 控制坐标轴刻度的显示-方法1

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

调用函数绘制图形,设置标尺:

ax1 = plt.subplot(121) ax1.set_xticks(range(0,251,50)) plt.grid(True,axis="x") ax2 = plt.subplot(122) ax2.set_xticks([]) plt.grid(True,axis="x") plt.show() 

运行结果:

img

3.5.3 控制坐标轴刻度的显示-方法2

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

调用函数绘制图形,设置标尺:

ax_new_1 = plt.subplot(221) plt.setp(ax_new_1.get_xticklabels(),visible=True) plt.setp(ax_new_1.get_xticklines(),visible=True) plt.grid(True,axis="x") ax_new_2 = plt.subplot(222) plt.setp(ax_new_2.get_xticklabels(),visible=True) plt.setp(ax_new_2.get_xticklines(),visible=False) plt.grid(True,axis="x") ax_new_3 = plt.subplot(223) plt.setp(ax_new_3.get_xticklabels(),visible=False) plt.setp(ax_new_3.get_xticklines(),visible=True) plt.grid(True,axis="x") ax_new_4 = plt.subplot(224) plt.setp(ax_new_4.get_xticklabels(),visible=False) plt.setp(ax_new_4.get_xticklines(),visible=False) plt.grid(True,axis="x") plt.show() 

运行结果:

img

3.5.4 移动坐标轴的位置

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(-2*np.pi,2*np.pi,200) y = np.sin(x) y1 = np.cos(x) 

调用函数绘制图形,设置标尺:

ax = plt.subplot(111) ax.plot(x,y,ls="-",lw=2,label="$\sin(x)$") ax.plot(x,y1,ls="-",lw=2,label="$\cos(x)$") ax.legend(loc="lower left") plt.title("$\sin(x)$"+"和"+"$\cos(x)$"+"函数") ax.set_xlim(-2*np.pi,2*np.pi) plt.xticks([-2*np.pi,-3*np.pi/2,-1*np.pi,-1*np.pi/2,0,(np.pi)/2,np.pi,3*np.pi/2,2*np.pi], ["$-2\pi$","$-3\pi/2$","$-\pi$","$-pi/2$","$0$","$pi/2$","$3pi/2$","$2\pi$","$2/pi$"]) ax.spines["right"].set_color("none") ax.spines["top"].set_color("none") ax.spines["bottom"].set_position(("data",0)) ax.spines["left"].set_position(("data",0)) ax.xaxis.set_ticks_position("bottom") ax.yaxis.set_ticks_position("left") plt.show() 

运行结果:

img

3.6 Matplotlib高级设置-签名与标记填充

3.6.1 调用签名形式的字典使用方法

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.linspace(0.0,2*np.pi,500) y = np.cos(x)*np.sin(x) 

调用函数绘制图形,设置标尺:

fig = plt.figure() ax = fig.add_subplot(111) font = {"family":"monospace","color":"maroon","weight":"bold","size":16} ax.plot(x,y,color="k",ls="-",lw=2) ax.set_title("keyword mode is 'fontdict=font'",fontdict=font) ax.text(1.5,0.4,"cos(x)*sin(x)",fontdict=font) ax.set_xlabel("time (h)",font) ax.set_ylabel(r"$\Delta$height (cm)",font) ax.set_xlim(0,2*np.pi) plt.show() 

运行结果:

img

3.6.2 标记填充样式的设置方法

导入支持库:

import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np 

设置中文显示:

mpl.rcParams["font.sans-serif"]=["SimHei"] mpl.rcParams["axes.unicode_minus"]=False 

设置绘图数据:

x = np.arange(3,11,1) y = np.linspace(1,1,8) 

调用函数绘制图形,设置标尺:

vfont_style = dict(family="sans-serif",color="saddlebrown",weight="semibold",size=16) line_marker_style = dict(linestyle=":",linewidth=2,color="cornflowerblue",markerfacecoloralt="lightgrey",marker="o",markersize=18) fig = plt.figure() ax = fig.add_subplot(111) fillstyleList = ["full","left","right","bottom","top","none"] ax.text(4,6.5,"fill styles",vfont_style) for i,fs in enumerate(fillstyleList): ax.text(0,i+0.4,"'{}'".format(fs),vfont_style) ax.plot(x,(i+0.5)*y,fillstyle=fs,line_marker_style) ax.set_xlim(-1,11) ax.set_ylim(0,7) ax.margins(0.3) ax.set_xticks([]) ax.set_yticks([]) plt.show() 

运行结果:

img

今天的文章 三、图形样式、Matplotlib高级设置分享到此就结束了,感谢您的阅读。
编程小号
上一篇 2024-12-21 21:27
下一篇 2024-12-21 21:21

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/92292.html