Python Pandas 并排绘制两个 BARH

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44049132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:37:33  来源:igfitidea点击:

Python Pandas Plotting Two BARH side by side

pythonpandasmatplotlibplot

提问by arnold

I am trying to make a plot that is similar like this, enter image description here

我正在尝试制作一个类似这样的情节, 在此处输入图片说明

The left hand side chart (the plot with legend) is derived from df_2, and the right hand side chart is derived from df_1.

左侧图表(带有图例的图)源自df_2,右侧图表源自df_1

However, I cannot make the two plots side-by-side share the y-axis.

但是,我不能让两个并排的图共享 y 轴。

Here is my current way to plot:

这是我目前的绘图方式:

df_1[target_cols].plot(kind='barh', x='LABEL', stacked=True, legend=False)
df_2[target_cols].plot(kind='barh', x='LABEL', stacked=True).invert_xaxis()
plt.show()

The code will resulted two plots in two different "canvas".

该代码将在两个不同的“画布”中生成两个图。

  1. How can I make them side-by-side sharing the y-axis?
  2. How can I remove the label in y-axis for the left hand side chart (chart derived from df_2)?
  1. 如何让它们并排共享 y 轴?
  2. 如何删除左侧图表(源自 的图表df_2)的y 轴标签?

Any suggestions will be much appreciated. Thanks.

任何建议将不胜感激。谢谢。

回答by ImportanceOfBeingErnest

You can create shared subplots using plt.subplots(sharey=True). Then plot the dataframes to the two subplots.

您可以使用plt.subplots(sharey=True). 然后将数据框绘制到两个子图中。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

a = np.random.randint(5,15, size=10)
b = np.random.randint(5,15, size=10)

df = pd.DataFrame({"a":a})
df2 = pd.DataFrame({"b":b})

fig, (ax, ax2) = plt.subplots(ncols=2, sharey=True)

ax.invert_xaxis()
ax.yaxis.tick_right()

df["a"].plot(kind='barh', x='LABEL',  legend=False, ax=ax)
df2["b"].plot(kind='barh', x='LABEL',ax=ax2)
plt.show()

enter image description here

在此处输入图片说明