【问题标题】:y tick labels on matplotlib subplots with sharey=Truey 在 matplotlib 子图上标记标签,sharey=True
【发布时间】:2018-07-23 19:56:05
【问题描述】:

使用 matplotlib 子图,我希望为不具有相同索引的数据帧提供通用 ylabel。但是子图的default behaviour 是使用第一列的标签。

df1=pd.DataFrame({'values':[2,3,5]},index=['a','b','c'])
df2=pd.DataFrame({'values':[1,1,1]},index=['a','b','d'])

_,a=plt.subplots(ncols=2,nrows=1,sharey=True,sharex=True)
df1.plot(kind='barh',ax=a[0],legend=False)
df2.plot(kind='barh',ax=a[1],legend=False)

此代码将显示一个子图,其中值“c”被标记为“d”。

我能想到的唯一方法是连接数据框创建一个公共索引。

df3=pd.concat([df1,df2],axis=1,sort=False)
df3.columns=['df1','df2']
_,a=plt.subplots(ncols=2,nrows=1,sharey=True,sharex=True)
df3.df1.plot(kind='barh',legend=False,ax=a[0])
df3.df2.plot(kind='barh',legend=False,ax=a[1])

有没有更优雅的解决方案?

【问题讨论】:

  • 您正在共享 y 轴。因此,如果需要,您找到的解决方案或以下答案中的解决方案是您能做的最好的。

标签: python-3.x matplotlib subplot


【解决方案1】:

您可以在绘图之前使用两个数据帧中的索引联合重新索引

new_index = df1.index.union(df2.index)
df1 = df1.reindex(new_index)
df2 = df2.reindex(new_index)

_,a=plt.subplots(ncols=2,nrows=1,sharex=True)
df1.plot(kind='barh',ax=a[0],legend=False)
df2.plot(kind='barh',ax=a[1],legend=False)

【讨论】: