1

I want to plot a bar and count plot in the same figure. But when I plot them with two different y-axis the two plot lay over each other (see picture). Is there an option to "shift" one of the plots to the side a bit?

fig, ax1 = plt.subplots(figsize=(15, 10))
ax2 = ax1.twinx()

ax1.bar(x=score[team], height=score[tot], color=colors)
ax2 = sns.countplot(x=dff[team], data=dff, palette=colors, order=team) 

Data description

score[team] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

enter image description here

0

1 Answer 1

1

While a little messy but manually changing bar width and position can get the job done.
I have used seaborn's barplot it's easier to plot dataframes

import seaborn as sns;sns.set()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

def change_width(ax, new_value,recenter=False) :
    for patch in ax.patches :
        current_width = patch.get_width()
        diff = current_width - new_value
        patch.set_width(new_value)
        if recenter==True:  
            patch.set_x(patch.get_x() + diff * .5) #To recenter the bars

df = sns.load_dataset('tips')
fig, ax1 = plt.subplots(figsize=(8, 8))
ax2 = ax1.twinx()

ax1 = sns.countplot(x='day', data=df)
change_width(ax1, 0.35)

ax2 = sns.barplot(x="day", y="total_bill", data=df,palette='viridis')
change_width(ax1, 0.35,True)

enter image description here The barplot's bar and countplot's bars can vary in height heavily, So I would say normalize the values, countplot doesn't support an Estimator so use barplot's estimator to find relative values

estimator=lambda x: len(x) / len(df) * 100

The change_width function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.