做这个教程的初心是:虽然plt.plot(x,y)
是一个简单方便的方式,但涉及到学术paper里的绘图教程往往会有很多细致的要求,需要进一步去细调图片,而这个时候则需要不断地百度百度百度,不妨写个教程从整体上整理一下。
本文参考资料:
https://zhuanlan.zhihu.com/p/93423829
https://matplotlib.org/1.5.1/faq/usage_faq.html#parts-of-a-figure
参考资料: https://matplotlib.org/1.5.1/faq/usage_faq.html#parts-of-a-figure
ax = fig.add_subplot(1,1,1)
,对于有子图的情形,每个subplot都是一个axes.subplot
的ipynb中详细介绍ax = fig.add_axes([left, bottom, width, height])
参数说明: left, bottom, width, height
百分比,即比例。
axes 和 subplot 是处于同一个级别的概念,都是在fig(画布)上选取一部分可控制的区域进而进行绘图等操作。区别在于axes自由度大,可以自己指定相关参数;而subplot则是在格式话等间隔将fig进行划分。可以说,subplot是axes的特例。
详情可以参考: https://www.zhihu.com/question/51745620
具体参考下图
ax.set_title()
ax.set_xlabel('x')
,ax.set_ylabel('y')
ax.set_aspect('equal')
ax.set_xlim(0,1)
, ax.set_ylim(0,1)
ax.grid(which = 'minor', axis = 'both')
这个可能是最常用的功能之一了,因为经常涉及到一些坐标轴的调整.
ax.set_xticks([0,1,2]) ;ax.set_yticks([0,1,2])
ax.set_xticklabels(['a', 'b', 'c'])
plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45 )
for tick in ax.xaxis.get_majorticklabels():
tick.set_horizontalalignment("right")
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
#make the background a little clear, to clear the original data
label.set_bbox(dict(facecolor='blue', edgecolor='None', alpha=0.65 ))
ax.xaxis.get_minorticklines()
不想看到刻度的标注,次刻度线不予显示。
for line in ax.xaxis.get_minorticklines():
line.set_visible(False)
这里共有四个可控参数:ax.spines['right']
,ax.spines['left']
,ax.spines['top']
,ax.spines['bottom']
以下选择其中的一个进行说明,其余自行扩展
ax.spines['right'].set_visible(False)
ax.spines['right'].set_color('b')
ax.xaxis.set_ticks_position('bottom')
,参数left,right,top
这个常见于图片大小无法再扩大,但图片中元素较多,放不下时,可以将ticks置于之上
ax.spines['left'].set_position(('data',0))
ax.grid(True)
ax.annotate(text,xy=(x,y))
text 为内容, 使用latex r'$xx$'
, xy 参数为显示的位置
r'$xxx$'
的方法matplotlib.style.use(u'grayscale')#xkcd,ggplot,classic
from matplotlib import rcdefaults
rcdefaults()
matplotlib.rc('font', family='serif')
matplotlib.rc('font', monospace='Times')
from matplotlib.font_manager import FontProperties
font1 = FontProperties(fname ='C:\Windows\Fonts\Times New Roman.ttf')
matplotlib使用matplotlibrc [matplotlib resource configurations]配置文件来自定义各种属性,我们称之为rc配置或者rc参数。在matplotlib中你可以控制几乎所有的默认属性:视图窗口大小以及每英寸点数[dpi],线条宽度,颜色和样式,坐标轴,坐标和网格属性,文本,字体等属性。matplotlib从下面的3个地方按顺序查找matplotlibrc文件:
这个参考 drawing_plot_paper_example2/图处理整体版本
使用matplotlib.font
进行初始化字体大小及字体设置
font1 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 10,
}
在接下来的label,ticks等使用font1即可 用法legend = plt.legend(handles=[A, B], prop=font1)
2. 初始化统一设置字体大小
matplotlib.rcParams.update({'font.size': 10})
or
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 10})
plt.rcParams.update({'font.family': 'Times New Roman'})
对于多图一开始即指定轴,后续方便对轴进行批量循环
fig = plt.figure(figsize=(8, 6.2))
axs_all =[]
rowNum = 3
colNum = 4
for i in range(rowNum):
axs_row = []
for j in range(colNum):
ax = fig.add_subplot(rowNum,colNum,i*colNum+j+1)
axs_row.append(ax)
axs_all.append(axs_row)
plt.figure(figsize = (10,6))
宽度一般不要>8(排版经验), 尽量满足黄金分割比,实在不行0.75plt.save_fig('test.png', dpi = 500)
一般而言使用png(无损保存), dpi设置根据期刊不同要求不同,一般500(记忆可能有误)plt.subplots_adjust(bottom=0.07,left=0.08,top=0.94,right=0.98,hspace=0.28,wspace=0.2)
#Axes
# The axes command allows more manual placement of the plots in the figure.
fig = plt.figure(figsize= (6,4))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
plt.show()
fig = plt.figure(figsize= (6,4))
fig.add_axes([0.1, 0.1, 0.8, 0.8],facecolor='g')
fig.add_axes([0.2, 0.3, 0.5, 0.5])
plt.show()
fig = plt.figure(figsize= (6,4))
fig.add_axes([0.1, 0.1, 0.5, 0.5])
fig.add_axes([0.2, 0.2, 0.5, 0.5])
fig.add_axes([0.3, 0.3, 0.5, 0.5])
fig.add_axes([0.4, 0.4, 0.5, 0.5])
plt.show()
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:522: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
max_open_warning, RuntimeWarning)
# Numbers 0 - 256
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
# cosine(X), sin(X)
C, S = np.cos(X)+2, np.sin(X)
fig = plt.figure(figsize = (6,4))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
axs = [ax1, ax2]
ax1.plot(X,C)
ax2.plot(C,S)
for ax in axs:
print(ax)
ax.set_title('test')
ax.set_xlabel('x'); ax.set_ylabel('y')
ax.set_xlim(np.min(X), np.max(X))
#ax.set_ylim
ax.set_yticks([0,1])
ax.set_xticks([-np.pi/2, 0, np.pi/2])
ax.set_xticklabels([r'-$\pi$',0, r'$\pi$' ])
ax.grid(True)
ax.annotate(r'$a$', xy = (0, 1),color="r",size=12)
ax1.annotate(r'$\cos(0) + 2 = 3$',
xy=(0, 3), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
fig.add_axes([0.1, 0.1, 0.2, 0.2],facecolor='g')
plt.show()
AxesSubplot(0.125,0.11;0.352273x0.77)
AxesSubplot(0.547727,0.11;0.352273x0.77)
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:522: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
max_open_warning, RuntimeWarning)
plt.figure(figsize = (6,4))
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
# cosine(X), sin(X)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C, color="blue", linewidth=2.5)
plt.plot(X, S, color="red", linewidth=2.5)
#Moving spines
# Spines are the lines connecting the axis tick marks and noting the boundaries of the data area. They can be placed at arbitrary positions and until now, they were on the border of the axis. We'll change that since we want to have them in the middle. Since there are four of them (top/bottom/left/right), we'll discard the top and right by setting their visibility to False and we'll move the bottom and left ones to coordinate 0 in data space coordinates.
# this is 2nd the axe preparation part
ax = plt.gca() # to get the present axe
#ax.spines['right'].set_visible(False)
ax.spines['right'].set_color('b')
#ax.spines['top'].set_visible(False)
ax.spines['top'].set_color('y')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.spines['bottom'].set_visible(True)
#ax.spines['bottom'].set_color('g')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
ax.spines['left'].set_visible(True)
ax.spines['left'].set_color('r')
plt.show()