简体   繁体   English

共享生成子图的轴matplotlib

[英]Sharing axes for generated subplots matplotlib

OK, I've got myself thoroughly confused... 好吧,我让自己彻底困惑了...
I have code that is generating a figure containing 8 sub-plots 我有代码生成包含8个子图的图形

import numpy as np
import matplotlib.pyplot as plt

names = ["one", "two", "three", "four", "five", "six", "seven", "eight"]
x = np.arange(1,11)
y = x**2.
z = x**1.5

fig = plt.figure()

fig.text(0.5, 0.02, "X axis", ha='center', fontsize=12)
fig.text(0.03, 0.5, "Y axis", va='center', rotation='vertical', fontsize=12)
palette = plt.get_cmap('tab10')

for name in names:
    i = names.index(name)+1 # What sub-plot are we on?
    graph = fig.add_subplot(4, 2, i)
# Add a new subplot to go in the grid (4x2)
    graph.set_title(f"plot {name}", fontsize=11)
    plot = graph.plot(x, y, color=palette(1))
    plot = graph.plot(x, z, color=palette(0))


plt.subplots_adjust(
top=0.93,
bottom=0.116,
left=0.124,
right=0.977,
hspace=0.972,
wspace=0.165)


plt.show()

It works fine, except I can't work out how to set the sub-plots so that they share x and y axes (I only want axes on the bottom edge for the x axis and left hand edge). 它工作正常,但我无法确定如何设置子图以共享x和y轴(我只希望x轴和左边缘的底边上的轴)。 All the examples I've been able to find seem to rely on each subplot having a different name that you can use to set sharex or sharey . 我能够找到的所有示例似乎都依赖于每个具有不同名称的子图,可用于设置sharexsharey Since I'm generating them as I go, there is nothing for the code to point to. 由于我一直在生成它们,因此代码没有指向的内容。

As per the comments, here is a working answer 根据评论,这是一个有效的答案

fig, axs = plt.subplots(4, 2, sharex='all', sharey='all')
graphs = axs.flatten()

for ax in graphs:
    ax.plot(x,y,color=palette(0))
    ax.plot(x,z,color= palette(1))

I've changed from the fig.addplot version above to a version which sets up all the sub-plots beforehand ( plt.subplots(y,x) ), and then just uses the loop to populate them. 我已经从上面的fig.addplot版本更改为一个可以预先设置所有子图的版本( plt.subplots(y,x) ),然后仅使用循环来填充它们。

Still don't seem to be able to remove the tick marks on the hidden axes labels though... 不过,似乎仍然无法删除隐藏的轴标签上的刻度线...

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

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