matplotlib多纵轴_matplotlib基础教程(学术版)

做这个教程的初心是:虽然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

3615d7f3e8f3a21a1011fbe0a884217b.gif e5ca3a0d5466c14ec66a8506192221aa.gif

基础概念

1. fig,ax,axes

fig: 画布对象

axes(句柄): 用法:ax = fig.add_subplot(1,1,1),对于有子图的情形,每个subplot都是一个axes.

其中如何根据 fig, 构建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
具体参考下图

3615d7f3e8f3a21a1011fbe0a884217b.gif

图像的元素

c8642ebdd0ab04a7878cb0f3f578b951.png

标题类

title, 标题: ax.set_title()

x_label, y_label, xy坐标轴的标题: ax.set_xlabel('x'),ax.set_ylabel('y')

axis类

横纵轴均等 ax.set_aspect('equal')

范围设置: ax.set_xlim(0,1), ax.set_ylim(0,1)

格子设置: ax.grid(which = 'minor', axis = 'both')

坐标轴 tick

这个可能是最常用的功能之一了,因为经常涉及到一些坐标轴的调整。

设置显示的位置 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 )

设置标签为右端 (shift labels to the right)

for tick in ax.xaxis.get_majorticklabels():
    tick.set_horizontalalignment("right")

设置标签的其它属性:字体, facecolor, edgecolor

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)

spines 类

这里共有四个可控参数:ax.spines['right'],ax.spines['left'],ax.spines['top'],ax.spines['bottom']

以下选择其中的一个进行说明,其余自行扩展

设置可见 ax.spines['right'].set_visible(False)

设置颜色 ax.spines['right'].set_color('b')

设置ticks位置 ax.xaxis.set_ticks_position('bottom'),参数left,right,top

这个常见于图片大小无法再扩大,但图片中元素较多,放不下时,可以将ticks置于之上

将坐标轴的原点设为中心点 ax.spines['left'].set_position(('data',0))

grid ,网格

ax.grid(True)

annotate,注释

ax.annotate(text,xy=(x,y))

text 为内容, 使用latex r'$xx$', xy 参数为显示的位置

3615d7f3e8f3a21a1011fbe0a884217b.gif

注意事项

如果在matplotlib 中输入latex 公式,使用r'$xxx$'的方法

设置style, matplotlib.style.use(u'grayscale')#xkcd,ggplot,classic

%matplotlib notebook
import matplotlib
from matplotlib import pyplot as plt

#%matplotlib tk
from matplotlib import rcdefaults
rcdefaults()
import numpy as np
import pandas as pd

fig, subplot, axes示意

#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)



<IPython.core.display.Javascript object>

6a6dfa9629af58083ede1ce24fb5bb0d.png

<IPython.core.display.Javascript object>

2cb1be0396990967968252090239da5e.png

<IPython.core.display.Javascript object>

7b4af15b35a054517c5179396c5fd006.png

 

图基础设置示意图

# 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)



<IPython.core.display.Javascript object>

44f6d8e95b9bac4e7f10161118fdf943.png

 

spines示意图

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()
<IPython.core.display.Javascript object>

0fb7fc2ea66570a4c3854516e947341d.png

编辑:庄桢

fc96c9558fbb50c3af58af6c27a18eba.gif

“交通科研Lab”:分享学习点滴,期待科研交流!

c55eecc230678f99b4290eb42a7f0dd9.png

如果觉得还不错

点这里???

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值