CharlesW
CharlesW

Reputation: 1072

Python Matplotlib/Seaborn/Jupyter - Putting bar plot in wrong place?

I'm using the following in a Jupyter notebook, using the latest Anaconda update (including Matplotlib 3.1.1,)

Thanks to SpghttCd, I have the code to do a stacked horizontal bar, but Seaborn puts it on a new plot below the default one.

How might I best fix this problem?

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data=pd.DataFrame(data={"R1":["Yes","Yes","Yes","No","No"]})
freq = data["R1"].value_counts(normalize=True)*100
fig,ax = plt.subplots()
freq.to_frame().T.plot.barh(stacked=True)

enter image description here

Upvotes: 0

Views: 185

Answers (1)

jlandercy
jlandercy

Reputation: 11002

You see two axes in Jupyter because you create a fresh one with plt.subplots() and pandas also creates another one.

If you need to reuse an existing axe, pass it to plotting method using ax switch:

fig, axe = plt.subplots()
freq.to_frame().T.plot.barh(stacked=True, ax=axe)

See pandas documentation for details, plotting method always exhibits an ax switch:

ax : Matplotlib axis object, optional

If you accept pandas creates it for you, as @Bharath M suggested, just issue:

axe = freq.to_frame().T.plot.barh(stacked=True)

Then you will see an unique axes and you can access it trough the variable axe.

Upvotes: 1

Related Questions