y 在 matplotlib 子图上用 sharey=True 勾选标签
y tick labels on matplotlib subplots with sharey=True
使用 matplotlib 子图我想为没有相同索引的数据帧使用通用的 ylabels。但是子图的 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])
有没有更优雅的解决方案?
在绘图之前,您可以使用两个数据帧中索引的并集重新索引
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)
使用 matplotlib 子图我想为没有相同索引的数据帧使用通用的 ylabels。但是子图的 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])
有没有更优雅的解决方案?
在绘图之前,您可以使用两个数据帧中索引的并集重新索引
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)