1. 共享坐标轴
当你通过
pyplot.subplot()
、
pyplot.axes()
函数或者
Figure.add_subplot()
、
Figure.add_axes()
方法创建一个
Axes
时,你可以通过
sharex
关键字参数传入另一个
Axes
表示共享X轴;或者通过
sharey
关键字参数传入另一个
Axes
表示共享Y轴。
共享轴线时,当你缩放某个
Axes
时,另一个
Axes
也跟着缩放。
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot([1,2,3,4,5])
ax2 = fig.add_subplot(212,sharex=ax1)
ax2.plot([7,6,5,4,3,2,1])
fig.show()
2. 创建多个 subplot
如果你想创建网格中的许多subplot
,旧式风格的代码非常繁琐:
# 旧式风格
fig=plt.figure()
ax1=fig.add_subplot(221)
ax2=fig.add_subplot(222,sharex=ax1,sharey=ax1)
ax3=fig.add_subplot(223,sharex=ax1,sharey=ax1)
ax4=fig.add_subplot(224,sharex=ax1,sharey=ax1)
新式风格的代码直接利用pyplot.subplots()
函数一次性创建:
# 新式风格的代码
fig,((ax1,ax2),(ax3,ax4))=plt.subplots(2,2,sharex=True,sharey=True)
ax1.plot(...)
ax2.plot(...)
它创建了Figure
和对应所有网格SubPlot
。你也可以不去解包而直接:
# 新式风格的代码
fig,axs=plt.subplots(2,2,sharex=True,sharey=True)
ax1=axs[0,0]
ax2=axs[0,1]
ax3=axs[1,0]
ax4=axs[1,1]
返回的axs
是一个nrows*ncols
的array
,支持numpy
的索引。
3. 调整横坐标不重叠
未调整前:
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
d0 = datetime.date(2016,1,1)
ndates = [d0+datetime.timedelta(i) for i in range(10)]
n_ys = [i*i for i in range(10)]
fig,ax = plt.subplots(1)
ax.plot(ndates,n_ys)
(1)matplotlib.dates.DateFormatter
当x
轴为时间日期时,有可能间隔太密集导致显示都叠加在一起。此时可以用matplotlib.figure.Figure.autofmt_xdate()
函数来自动调整X轴日期的显式。
也可以调整X轴的显示格式。当X轴为时间时,其显示由Axes.fmt_xdata
属性来提供。该属性是一个函数对象或者函数,接受一个日期参数,返回该日期的显示字符串。matplotlib
已经提供了许多date formatter
,你可以直接使用ax.fmt_xdata=matplotlib.dates.DateFormatter('%Y-%m-%d')。
fig2,ax2 = plt.subplots(1)
ax2.plot(ndates,n_ys)
fig2.autofmt_xdate() # 调整x轴时间的显示
ax2.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') # 格式化器
plt.show()
(2)plt.xticks(rotation=顺时针旋转角度)
fig3,ax3 = plt.subplots(1)
ax3.plot(ndates,n_ys)
plt.xticks(rotation=25)
plt.tight_layout()
plt.show()
(3)ax.set_xticklabels(rotation=顺时针旋转角度)
fig4,ax4 = plt.subplots(1)
ax4.plot(ndates,n_ys)
ax4.set_xticklabels(ndates,rotation=25,ha="right")
plt.tight_layout()
plt.show()
4. 放置 text box
当你在Axes
中放置text box
时,你最好将它放置在axes coordinates
下,这样当你调整X轴或者Y轴时,它能够自动调整位置。
你也可以使用Text
的.bbox
属性来让这个Text
始终放在某个Patch
中。其中.bbox
是个字典,它存放的是该Patch
实例的属性。
ax.text(x, y, s, fontdict=None, withdash=False, **kwargs)
功能:将文本s添加到数据坐标中位置x,y的轴上。
x,y:张量,放置文本的位置。 默认情况下,这是在数据坐标中。 可以使用变换参数来更改坐标系。
s:文本
fontdict:字典,可选,覆盖默认文本属性的字典。 如果fontdict为None,则默认值由rc参数确定。
withdash:布尔值,可选,默认值:False。创建一个〜matplotlib.text.TextWithDash实例,而不是一个〜matplotlib.text.Text实例。
你可以使用对齐参数horizontalalignment
,verticalalignment
和multialignment
来布置文本。
horizontalalignment
控制文本的x
位置参数表示文本边界框的左边,中间或右边。
verticalalignment
控制文本的y
位置参数表示文本边界框的底部,中心或顶部。
multialignment
,仅对于换行符分隔的字符串,控制不同的行是左,中还是右对齐。
这里是一个使用text()
命令显示各种对齐方式的例子。 在整个代码中使用transform = ax.transAxes
,表示坐标相对于轴边界框给出,其中0,0
是轴的左下角,1,1
是右上角。
import matplotlib.pyplot as plt
import numpy as np
fig,ax = plt.subplots(1)
x = 30 * np.random.randn(10000)
mu = x.mean()
median = np.median(x)
sigma = x.std()
textstr = '$\mu=%.2f$ \n $\mathrm{median}=%.2f$ \n $\sigma=%.2f$'%(mu,median,sigma)
ax.hist(x,50)
props=dict(boxstyle='round',facecolor='wheat',alpha=0.5)
ax.text(0.05,0.95,textstr,transform=ax.transAxes,fontsize=14,verticalalignment='top',bbox=props)
fig.show()
5. LATEX文字
要想在文本中使用LATEX,你需要使用'$...$'这种字符串(即使用'$'作为界定符)。通常建议使用raw字符串,即r'$...$'的格式,因为原生字符串不会转义'\',从而使得大量的LATEX词法能够正确解析。
sns.set(style='ticks')
sns.set_context(rc={'lines.linewidth':5})
plt.xlim((10,100.5))
plt.ylim((0,41))
plt.xticks(np.arange(10, 100.5, 15))
plt.yticks(np.arange(0,41,10))
# "greyish", "faded green",
colors = ["windows blue", "dark green", "slate grey"]
palette = sns.xkcd_palette(colors)
ax = sns.lineplot(x="phi", y="MAPE",hue = 'alg', style='alg',data=df_mape_change_phi, markers = False,palette=palette)
# - 实线-- 短线-.短点相间线:虚点线
# ax.lines[0].set_linestyle("-")
# ax.lines[1].set_linestyle("-.")
# ax.lines[2].set_linestyle("--")
plt.xlabel(r'$\varphi$', fontdict={'color': 'black','family': 'Times New Roman','size': 18})
plt.ylabel(r'MAPE($\times 10^{-3}$)', fontdict={'color': 'black','family': 'Times New Roman','size': 18})
plt.legend(['IMTEC','ER','SRD'],prop={'style': 'italic'},handlelength=4)#图例
plt.grid(True)
plt.tight_layout()
plt.savefig('local_pic/phi_mape.jpg',dpi=600)
# plt.savefig('loc_svg/TD_precision_tasknum.svg')
plt.show()
6. 平移坐标轴
Axes.spines
是个字典,它存放了四个键,分别为:
Axes.spines['left'],
Axes.spines['right'],
Axes.spines['top'],
Axes.spines['bottom']
他们都是一个matplotlib.spines.Spine
对象,该对象继承自matplotlib.patches.Patch
对象,主要是设置图形边界的边框。
Spine.set_color('none')
:不显示这条边线
Spine.set_position((position))
:将边线移动到指定坐标,其中position
是一个二元元组,指定了 (position type,amount)
,position type
可以是:
outward
:在绘图区域之外放置边线,离开绘图区域的距离由 amount
指定(负值则在会去区域内绘制)
axes
:在 Axes coordinate
内放置边线(从 0.0 到 1.0 )
data
:在 data coordinate
内放置边线
你也可以指定position
为:'center'
,等价于 ('axes',0.5)
;或者 'zero'
,等价于 ('data',0.0)
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-2,2,num=100)
Y = np.sin(X)
fig = plt.figure(figsize=(8,4))
# ax1
ax1 = fig.add_subplot(1,2,1)
ax1.plot(X,Y)
ax1.set_title('default')
# ax2
ax2 = fig.add_subplot(1,2,2)
ax2.plot(X,Y)
ax2.spines['right'].set_color('none') # 不显示右边框
ax2.spines['top'].set_color('none') # 不显示上边框
ax2.xaxis.set_ticks_position('bottom') # 设置x坐标轴为下边框
ax2.yaxis.set_ticks_position('left') # 设置y坐标轴为左边框
ax2.spines['bottom'].set_position(('data',0))# 设置x轴, y轴在(0, 0)的位置
ax2.spines['left'].set_position(('data',0))
ax2.set_title('move axis')
7. 清除绘图
(1)通过pyplot清除绘图
pyplot.cla()
:清除current axis
。非当前axis
不受影响
pyplot.clf()
:清除current figure
。但是它不关闭window
pyplot.close()
:关闭window
(2)通过面向对象的方法
Figure.clf()
:清除该Figure
对象的所有内容。
8. 清除X坐标和Y坐标
Axes.set_xticks(())
Axes.set_yticks(())
Axes.set_axis_off() #清除tick和边框
9. 设置中文
在linux
下,为了支持中文,则在开头设置:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #matplotlib 中文字体