Matplotlib中具有公共y轴标签的公共x轴上的多个图

时间:2019-08-18 16:39:58

标签: python python-3.x matplotlib

我已经编写了以下最少的Python代码,以便在同一X轴上绘制x的各种功能。

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from cycler import cycler

cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']

xlabel='$X$'; ylabel='$Y$'

### Set tick features 
plt.tick_params(axis='both',which='major',width=2,length=10,labelsize=18)
plt.tick_params(axis='both',which='minor',width=2,length=5)
#plt.set_axis_bgcolor('grey') # Doesn't work if I uncomment!



lines = ["-","--","-.",":"]

Nlayer=4
f, axarr = plt.subplots(Nlayer, sharex=True)

for a in range(1,Nlayer+1):

     X = np.linspace(0,10,100)
     Y = X**a
     index = a-1 + np.int((a-1)/Nlayer)
     axarr[a-1].plot(X, Y, linewidth=2.0+index, color=cycle[a], linestyle = lines[index], label='Layer = {}'.format(a)) 
     axarr[a-1].legend(loc='upper right', prop={'size':6})


#plt.legend()


# Axes labels
plt.xlabel(xlabel, fontsize=20)
plt.ylabel(ylabel, fontsize=20)

plt.show()

但是,这些图未在X轴上合并在一起,因此我无法获得通用的Y轴标签。它实际上标记了最后一个图(请参见附图)。此外,我还得到了一个我无法摆脱的空白情节。

我正在使用Python3。

enter image description here

1 个答案:

答案 0 :(得分:2)

以下代码将产生预期的输出:

  • 没有在创建实际的plt.tick_params之前由于两次fig调用而创建的空白图
  • 使用gridspec_kw的{​​{1}}参数,您可以控制subplots环境的rowscols之间的空间,以便加入不同的层情节
  • 具有唯一且居中的公用subplots,其中使用ylabel并具有相对位置和fig.text自变量(对rotation进行了同样的处理以获得均匀的最终结果)。可能有人注意到,也可以通过在像xlabel这样的常规调用之后将ylabelax.yaxis.set_label_coords()重新定位来实现。
ax.set_ylabel()

带有轴import numpy as np import matplotlib.pyplot as plt cycle = plt.rcParams['axes.prop_cycle'].by_key()['color'] xlabel='$X$'; ylabel='$Y$' lines = ["-","--","-.",":"] Nlayer = 4 fig, axarr = plt.subplots(Nlayer, sharex='col',gridspec_kw={'hspace': 0, 'wspace': 0}) X = np.linspace(0,10,100) for i,ax in enumerate(axarr): Y = X**(i+1) ax.plot(X, Y, linewidth=2.0+i, color=cycle[i], linestyle = lines[i], label='Layer = {}'.format(i+1)) ax.legend(loc='upper right', prop={'size':6}) ,第一个选择:

labels

或者:

fig.text(0.5, 0.01, xlabel, va='center')
fig.text(0.01, 0.5, ylabel, va='center', rotation='vertical')

给出:

output_figure

我还简化了您的# ax is here, the one of the last Nlayer plotted, i.e. Nlayer=4 ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) # change y positioning to be in the horizontal center of all Nlayer, i.e. dynamically Nlayer/2 ax.yaxis.set_label_coords(-0.1,Nlayer/2) 循环,方法是在循环for时使用enumerate具有一个自动计数器i