Home > OS >  Axis transformation for subplot in matplotlib
Axis transformation for subplot in matplotlib

Time:07-16

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

test 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()

test 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()

test 2

CodePudding user response:

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(). This means you're trying to plot outside the axes axs[1,0].

So you need to change base = pyplot.gca().transData to

base = axs[1, 0].transData

enter image description here

  • Related