Space between groups in horizontal barplots

59 views Asked by At

Im trying to make a horizontal barplot, where there's space between the 4-team bars. I've tried inserting another team, but for some reason it overlaps with the other bars. My code looks like this

bars = (0, 1, 2, 3)
X = np.arange(len(bars))
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
plt.xlim([-33, 30])
plt.ylim([-0.2, 5])
ax.barh(X + 0.00, teamstat[0], color = ('#00B2A9'), edgecolor=('#BED4E9'), height = 0.25, label='Grizzlies')
ax.barh(X + 0.25, teamstat[1], color = ('#552583'), edgecolor=('#FDB927'), height = 0.25, label='Suns')
ax.barh(X + 0.50, teamstat[2], color = ('#F9AD1B'), edgecolor=('#1D1160'), height = 0.25, label='Lakers')
ax.barh(X + 0.75, teamstat[3], color = ('#00471B'), edgecolor=('#0000'), height = 0.25,  label='Bucks')
osz = 0
y = ['Free Throws','Turnovers','Fouls','Blocks']
plt.barh(y, osz)
plt.title('%dif regular to bub')
    MEM = [3.81125,  2.978723, 12.962227, -18.78327]
PHX = [6.024351, -18.708139, -5.718813, -7.07449]
LAL = [0.254398, 7.531717, 3.579793, -27.362832]
MIL = [-2.015801, 15.402352, 15.839965, -11.223886]
FAK = [10.978723, 5.978723, 2.978723, 3.978723]
teamstat = [MEM, PHX, LAL, MIL]

output

1

There are 1 answers

0
JohanC On

One approach is to use np.linspace to divide the available space into N equal parts:

from matplotlib import pyplot as plt
import numpy as np

MEM = [3.81125, 2.978723, 12.962227, -18.78327]
PHX = [6.024351, -18.708139, -5.718813, -7.07449]
LAL = [0.254398, 7.531717, 3.579793, -27.362832]
MIL = [-2.015801, 15.402352, 15.839965, -11.223886]
FAK = [10.978723, 5.978723, 2.978723, 3.978723]
teamstats = [MEM, PHX, LAL, MIL, FAK]
teamnames = ['Grizzlies', 'Suns', 'Lakers', 'Bucks', 'Fak']

X = np.arange(len(teamstats[0]))
fig, ax = plt.subplots()

facecolors = ['#00B2A9', '#552583', '#F9AD1B', '#00471B', 'mediumorchid']
edgecolors = ['#BED4E9', '#FDB927', '#1D1160', 'black', 'black']

group_height = 0.95
indents = np.linspace(0, group_height, len(teamnames), endpoint=False)
for teamstat, teamname, facecolor, edgecolor, indent in zip(teamstats, teamnames, facecolors, edgecolors, indents):
    ax.barh(X + indent, teamstat[0], height=group_height / len(teamnames),
            color=facecolor, edgecolor=edgecolor, label=teamname)

y = ['Free Throws', 'Turnovers', 'Fouls', 'Blocks']
ax.set_yticks(range(len(y)))
ax.set_yticklabels(y)
ax.set_title('%dif regular to bub')
# ax.set_xlim([-33, 30])
# ax.set_ylim([-0.2, 5])
ax.legend(bbox_to_anchor=[1.02, 1.02], loc='upper left')
plt.tight_layout()
plt.show()

resulting plot