Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

matplotlib - Python: Suplots with two secondary-axis

This is a follow up to this question. I thank maxnoe for the help.

I would like to add a second secondary axis to each of my subplots similarly like in this example but in a subplot.

I tried to set up my figure using:

fig, ((ax1a, ax2a), (ax3a, ax4a)) = host_subplot(4,4, axes_class=AA.Axes)

but I get TypeError: 'AxesHostAxesSubplot' object is not iterable and

ValueError: Illegal argument(s) to subplot: (4, 4)

Is it possible to have a subplot where each figure has two secondary axes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

plt.subplots is a convenience function for creating the figure and multiple subplots at once. However, its powers are limited. If you want to create special axes, you will have to initialize them the 'hard' way.

Adapting the example you mentioned for a grid of 2x2 subplots with the shown properties. To avoid to much repetetive code, i'm using a for loop to initialize all the plots and store them in a list of dictionaries.

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

subplots = []
rows = 2
columns = 2

for n in range(rows * columns):
    host = host_subplot(rows, columns, n + 1, axes_class=AA.Axes)

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

    offset = 60

    par2.axis["right"] = par2.get_grid_helper().new_fixed_axis(
        loc="right",
        axes=par2,
        offset=(offset, 0),
    )

    par2.axis["right"].toggle(all=True)

    host.set_xlabel("Distance")
    host.set_ylabel("Density")
    par1.set_ylabel("Temperature")
    par2.set_ylabel("Velocity")

    subplots.append({
        'density': host,
        'temperature': par1,
        'velocity': par2,
    })


subplots[0]['density'].plot([1, 2, 3])
subplots[2]['temperature'].plot([1, 2, 3])
plt.tight_layout()
plt.savefig('result2.png', dpi=300)

Result: result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...