matplotlib 高级用法实例--共享x轴

本文介绍了如何使用Matplotlib创建两个子图并实现共享X轴的功能。通过实例演示了如何让两个子图的X轴在缩放和平移时保持同步,便于同时观察不同数据随时间变化的趋势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://localhost:8888/notebooks/duanqs/matplotlib_advanced_example.ipynb

我不会弄呀, 刚才从matplotlib文档里吧示例用jupyter notebook跑了一遍, 很不错的笔记. 

如何才能把它写到博客里呢. 

python代码和mk代码混合在一起了, 很难看呀!!!

 1 Our Favorite Recipes — Matplotlib 1.5.1 documentation
 2 http://matplotlib.org/users/recipes.html
 3 Our Favorite Recipes
 4 Here is a collection of short tutorials, examples and code snippets that illustrate some of the useful idioms and tricks to make snazzier figures and overcome some matplotlib warts.
 5 Sharing axis limits and views It’s common to make two or more plots which share an axis, e.g., two subplots with time as a common axis. When you pan and zoom around on one, you want the other to move around with you. To facilitate this, matplotlib Axes support a sharex and sharey attribute. When you create a subplot() or axes() instance, you can pass in a keyword indicating what axes you want to share with
 6 In [1]:
 7 
 8 import matplotlib 
 9 import numpy as np
10 import matplotlib.pyplot as plt
11 %matplotlib inline
12 import matplotlib 
13 In [2]:
14 
15 t = np.arange(0, 10, 0.01)
16 17 ax1 = plt.subplot(211)
18 ax1.plot(t, np.sin(2*np.pi*t))
19 20 ax2 = plt.subplot(212, sharex=ax1)
21 ax2.plot(t, np.sin(4*np.pi*t))
22 Out[2]: 
23 [<matplotlib.lines.Line2D at 0x559b710>]

 


 

转载于:https://www.cnblogs.com/duan-qs/p/5750936.html

### 使用 Matplotlib 创建双 Y 图表 为了创建一个带有两个不同 Y 的图表,可以利用 `twinx()` 方法来增加一个新的坐标共享相同的 X 坐标。下面是一个具体的例子展示如何实现这一点: ```python import numpy as np import matplotlib.pyplot as plt # 定义数据点 x = np.linspace(0, 10, 100) y1 = np.sin(x) * 100 # 左侧Y的数据 y2 = (np.cos(x) + 1) / 2 # 右侧Y的数据 # 初始化图形对象并设置大小 fig, ax1 = plt.subplots(figsize=(10, 5)) color = 'tab:blue' ax1.set_xlabel('Time') ax1.set_ylabel('Angular Velocity', color=color) # 设置左侧Y标签颜色匹配线条颜色 ax1.plot(x, y1, color=color) ax1.tick_params(axis='y', labelcolor=color) # 实例化第二个Y并与第一个共享X ax2 = ax1.twinx() color = 'tab:red' ax2.set_ylabel('Heading Angle', color=color) # 设置右侧Y标签颜色匹配线条颜色 ax2.plot(x, y2, color=color) ax2.tick_params(axis='y', labelcolor=color) plt.title('Dual-Y Axis Chart Example') fig.tight_layout() # 自动调整子图参数使之填充整个图像区域 plt.show() ``` 这段代码展示了如何在同一张图上同时显示两种不同类型的数据——一种是以蓝色表示的角度速度(左侧 Y ),另一种是以红色表示的方向角度(右侧 Y )。通过这种方式,可以在同一视图内比较这两种不同的测量值。 对于更复杂的场景,比如希望添加额外的信息如网格线、注解或是改变样式等,则可以根据需求进一步自定义图表属性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值