在python中实现多坐标轴的绘制

本文介绍了如何在Python中创建多坐标轴的图形,并展示了具体的实现效果。关键步骤包括设置边框、填充以及坐标轴可见性。代码示例提供了一个详细的实现过程。

在python中实现多坐标轴的绘制

实现的效果如下图所示:
其中注意点:

  • ax.set_frame_on(True) #frame代表边框

  • ax.patch.set_visible(False) #patch代表填充

  • for sp in ax.spines.values(): #spines代表坐标轴
    sp.set_visible(False) #spines.values代表坐标轴上的值

下面是代码:

import matplotlib.pyplot as plt

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)             #frame代表边框
    ax.patch.set_visible(False)       #patch代表填充
    for sp in ax.spines.values():     #spines代表坐标轴
        sp.set_visible(False)         #spines.values代表坐标轴上的值

fig, host = plt.subplots()
fig.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

# Offset the right spine of par2.  The ticks and label have already been
# placed on the right by twinx above.
par2.spines["right"].set_position(("axes", 1.2))

# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible.  First, activate the frame but make the patch
# and spines invisible.
#激活边框,让par1与par2重合,但是取消par2的填充(否则会出现覆盖),并且使par2坐标轴不可见
make_patch_spines_invisible(par2)
# Second, show the right spine.
#使新建的par2的坐标轴显示
par2.spines["right"].set_visible(True)

p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label="Den
Python中,常用的绘库有Matplotlib和Seaborn等,以下以Matplotlib为例介绍绘制y轴坐标的方法。 ### 单Y轴坐标绘制 使用Matplotlib绘制单Y轴坐标是基础操作,以下是简单示例: ```python import matplotlib.pyplot as plt import numpy as np # 生成数据 x = np.linspace(0, 10, 100) y = np.sin(x) # 绘制像 plt.plot(x, y) # 设置标题和坐标轴标签 plt.title('Single Y-axis Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') # 显示像 plt.show() ``` 在这个示例中,使用`plt.plot()`函数绘制一个简单的正弦曲线,然后使用`plt.ylabel()`函数为y轴添加了标签。 ### 双Y轴坐标绘制 若需要在一个中展示两个不同量级或类型的数据,可以使用双Y轴。关键函数是`twinx()`,示例如下: ```python import matplotlib.pyplot as plt import numpy as np # 生成数据 x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.exp(x) # 创建第一个坐标轴 fig, ax1 = plt.subplots() # 绘制第一条曲线 ax1.plot(x, y1, 'b-') ax1.set_xlabel('X-axis') ax1.set_ylabel('Y1-axis', color='b') ax1.tick_params(axis='y', labelcolor='b') # 创建第二个坐标轴 ax2 = ax1.twinx() # 绘制第二条曲线 ax2.plot(x, y2, 'r-') ax2.set_ylabel('Y2-axis', color='r') ax2.tick_params(axis='y', labelcolor='r') # 设置标题 plt.title('Dual Y-axis Plot') # 显示像 plt.show() ``` 这里使用`twinx()`函数创建了第二个y轴,通过不同的颜色区分两个y轴及其对应的曲线
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值