如何在matplotlib中生成链接轴 [英] How to generate linked-axis in matplotlib

查看:57
本文介绍了如何在matplotlib中生成链接轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建带有链接x轴s.t的图.顶部和底部刻度/标签是单位(焦耳和千焦耳)的度量.我已经看到了sharex等示例,但我的需求如下:

I'm trying to create a plot with linked x-axis s.t. top and bottom tick/labels are measurement of units (Joules and kJoules). I've seen examples with sharex etc but my needs are following:

  1. 如何使轴链接到从第一个轴生成第二个刻度线/标签的位置
  2. 在一个轴上更改限制时,另一根轴应自动更新

最简单的事情(一点也不优雅)是创建两个 x 变量:

The easiest thing (not at all elegant) would be to create two x-variables:

x1 = np.arange(0,10000,1000)
x2 = x1/1000.
y = np.random.randint(0,10,10)

fig, ax = plt.subplots()
ax.plot(x1, y, 'ro')

ax2 = ax.twiny()
ax2.plot(x2,y,visible=False)
plt.show()


这会产生以下结果:


This produces the following:

但是当我尝试在任何一个上设置 x 轴限制时,事情就会中断.例如,执行 ax2.set_xlim(2,5)只会更改顶部的轴.

But things break when I attempt to set the x-axis limits on either. E.g., doing ax2.set_xlim(2,5) only changes the axis on top.

既然我已经知道x1和x2是相关的,那么我应该如何设置绘图,以便当我更改一个时,另一个会自动处理.

Since I already know that x1 and x2 are related, how should I set up the plot so that when I change one, the other is automatically taken care of.

非常感谢

推荐答案

似乎您想使用具有指定比例的寄生轴.在 matlpotlib 站点上有一个 example,稍加修改的版本如下.

It seems that you want to use a parasite axes with a specified scale. There is an example of this on the matlpotlib site, slightly modified version is below.

import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
import numpy as np

# Set seed for random numbers generator to make data recreateable
np.random.seed(1235) 

# Define data to be plotted
x1 = np.arange(0,10000,1000)
x2 = x1/1000.
y1 = np.random.randint(0,10,10)
y2 = y1/5.

# Create figure instance
fig = plt.figure()

# Make AxesHostAxesSubplot instance
ax = SubplotHost(fig, 1, 1, 1)

# Scale for top (parasite) x-axis: makes top x-axis 1/1000 of bottom x-axis
x_scale = 1000.
y_scale = 1.

# Set scales of parasite axes to x_scale and y_scale (relative to ax)
aux_trans = mtransforms.Affine2D().scale(x_scale, y_scale)

# Create parasite axes instance
ax_parasite = ax.twin(aux_trans) 
ax_parasite.set_viewlim_mode('transform')

fig.add_subplot(ax)

# Plot the data
ax.plot(x1, y1)
ax_parasite.plot(x2, y2)

# Configure axis labels and ticklabels
ax.set_xlabel('Original x-axis')
ax_parasite.set_xlabel('Parasite x-axis (scaled)')
ax.set_ylabel('y-axis')
ax_parasite.axis['right'].major_ticklabels.set_visible(False)

plt.show()

这给出了下面的输出

如果您更改 ax 实例的限制,ax_parasite 实例的限制会自动更新:

If you change the limits of the ax instance, the limits of the ax_parasite instance are updated automatically:

# Set limits of original axis (parasite axis are scaled automatically)
ax.set_ylim(0,12)
ax.set_xlim(500,4000)

这篇关于如何在matplotlib中生成链接轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆