简体   繁体   English

matplotlib中子图的轴变换

[英]Axis transformation for subplot in matplotlib

It seems that axis transformation for a subplot does not work as for a single plot.似乎子图的轴转换不像单个图那样起作用。

import numpy as np
data = np.random.randn(100)
from matplotlib import pyplot,  transforms

# first of all, the base transformation of the data points is needed
base = pyplot.gca().transData
rot = transforms.Affine2D().rotate_deg(90)

# define transformed line
line = pyplot.plot(data, 'r--', transform= rot + base)
# or alternatively, use:
# line.set_transform(rot + base)

pyplot.show()

测试 0

When using this scheme for a subplot it works erratically.当将此方案用于子图时,它会不稳定地工作。 It works for the last subplot as shown below.它适用于最后一个子图,如下所示。


import numpy as np
from matplotlib import pyplot,  transforms

# Example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
##########################################

fig, axs = pyplot.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')

axs[1, 0].plot(x, y, 'tab:green' )
axs[1, 0].set_title('Axis [1, 0]')

base = pyplot.gca().transData
rot = transforms.Affine2D().rotate_deg(90)

axs[1, 1].plot(x, -y, 'tab:red' ,   transform = rot + base )
axs[1, 1].set_title('Axis [1, 1]')

for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
    ax.label_outer()

测试 1

When trying this for the third subplot (example below), the trace is now shown.当为第三个子图(下面的示例)尝试此操作时,现在显示了跟踪。 Could someone help to solve this issue.有人可以帮助解决这个问题。 Thanks.谢谢。

# Example data to display
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
##########################################

fig, axs = pyplot.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')

base = pyplot.gca().transData
rot = transforms.Affine2D().rotate_deg(90)

axs[1, 0].plot(x, y, 'tab:green' ,   transform = rot + base  )
axs[1, 0].set_title('Axis [1, 0]')

axs[1, 1].plot(x, -y, 'tab:red' )
axs[1, 1].set_title('Axis [1, 1]')

for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
    ax.label_outer()

测试 2

When you do pyplot.gca() after fig, axs = pyplot.subplots(2, 2) , the current axes is axs[1,1] as you can verify by pyplot.gca().get_gridspec() .当您在fig, axs = pyplot.subplots(2, 2)之后执行pyplot.gca()时,当前轴为axs[1,1] ,您可以通过pyplot.gca().get_gridspec()进行验证。 This means you're trying to plot outside the axes axs[1,0] .这意味着您正在尝试在轴axs[1,0]之外绘图。

So you need to change base = pyplot.gca().transData to所以你需要将base = pyplot.gca().transData

base = axs[1, 0].transData

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM