Sharing a yaxis label with two of three subplots in pyplot

ぐ巨炮叔叔 提交于 2021-01-27 02:56:41

问题


I have the following code which produces the plot shown.

mport matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec
import numpy as np

One = range(1,10)
Two = range(5, 14) 
l = len(One)
fig = plt.figure(figsize=(10,6))
gs = gridspec.GridSpec(3, 1, height_ratios=[5, 3, 3]) 

ax0 = plt.subplot(gs[0])
ax0.bar(range(l), Two)
plt.ylabel("Number of occurrence")

ax1 = plt.subplot(gs[1], sharey=ax0)
ax1.bar(range(l), Two)

ax2 =  plt.subplot(gs[2])
ax2.bar(range(l), One)

plt.show()

enter image description here

I want the ylabel (" Number of occurrence") to be shared between first and second plot, that is, it should occur in the center left of first and second plot. How do I do that?


回答1:


The best way I can think of is to add the text to the figure itself and position it at the center (figure coordinates of 0.5) like so

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

One = range(1,10)
Two = range(5, 14)
l = len(One)
fig = plt.figure(figsize=(10,6))
gs = gridspec.GridSpec(3, 1, height_ratios=[5, 3, 3])

ax0 = plt.subplot(gs[0])
ax0.bar(range(l), Two)

ax1 = plt.subplot(gs[1], sharey=ax0)
ax1.bar(range(l), Two)

ax2 =  plt.subplot(gs[2])
ax2.bar(range(l), One)

fig.text(0.075, 0.5, "Number of occurrence", rotation="vertical", va="center")

plt.show()



回答2:


I think this question is more of creating multiple-axis if said in the right terms. I would like to point you to the question I asked and the answer I received which gives you the solution to create multiple-axis for the plot.

Link to the similar problem solution in Matplotlib: Using Multiple Axis

Link to the other related question is:multiple axis in matplotlib with different scales




回答3:


not a very sophisticated solution, but would this work? Replace

plt.ylabel("Number of occurrence")

with

plt.ylabel("Number of occurrence", verticalalignment = 'top')

[edit]

for my version of 64 bit python (2.7.3) I needed to make a small change

plt.ylabel("Number of occurrence", horizontalalignment = 'right')

here's what it looks like to me, is this not what you want?

enter image description here




回答4:


You can also adjust the position manually, using the y parameter of ylabel:

import matplotlib.pyplot as plt 
import matplotlib.gridspec as gridspec
import numpy as np

One = range(1,10)
Two = range(5, 14) 
l = len(One)
fig = plt.figure(figsize=(10,6))
gs = gridspec.GridSpec(3, 1, height_ratios=[5, 3, 3]) 

ax0 = plt.subplot(gs[0])
ax0.bar(range(l), Two)
plt.ylabel("Number of occurrence", y=-0.8)          ##  ← ← ← HERE

ax1 = plt.subplot(gs[1], sharey=ax0)
ax1.bar(range(l), Two)

ax2 =  plt.subplot(gs[2])
ax2.bar(range(l), One)

plt.show()



来源:https://stackoverflow.com/questions/20660588/sharing-a-yaxis-label-with-two-of-three-subplots-in-pyplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!