Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Plotting Two BARH side by side

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.

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

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)?
like image 510
arnold Avatar asked May 18 '17 13:05

arnold


1 Answers

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

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

like image 57
ImportanceOfBeingErnest Avatar answered Nov 25 '22 09:11

ImportanceOfBeingErnest