добавить пробел между барами в каждой подгруппе в pandas барплот - PullRequest
1 голос
/ 01 апреля 2020

У меня есть такой фрейм данных:

    chart = pd.DataFrame({'test1_bottom': {'Information Technology': 0.2533668392286677,
  'Health Care': 0.15018887027604233,
  'Financials': 0.11250374171121448,
  'Communication Services': 0.10598698851685082,
  'Consumer Discretionary': 0.09930980115655588,
  'Industrials': 0.08341663798744221,
  'Consumer Staples': 0.077755633372036,
  'Utilities': 0.03633802369644037,
  'Real Estate': 0.030599694393051324,
  'Energy': 0.026211182457138587},
 'test1_top': {'Information Technology': 0.2533668392286677,
  'Health Care': 0.15018887027604233,
  'Financials': 0.11250374171121448,
  'Communication Services': 0.10598698851685082,
  'Consumer Discretionary': 0.09930980115655588,
  'Industrials': 0.08341663798744221,
  'Consumer Staples': 0.077755633372036,
  'Utilities': 0.03633802369644037,
  'Real Estate': 0.030599694393051324,
  'Energy': 0.026211182457138587}})

Я пытаюсь добавить пробелы между барами в каждой подгруппе, так как моя метка значения на каждом баре перекрывается:

figsize=(9,4)
ax = chart.iloc[::-1].plot.barh(figsize=figsize, color=['#0574A0','#FF5233'],width=0.5);
for p in ax.patches:
    v = ax.annotate("{:,.2%}".format(p.get_width()), (p.get_width(), p.get_y() + p.get_height()/4), xytext=(4, -1), 
                textcoords='offset points',ha='left');
plt.legend(loc='lower right',fontsize=10)
plt.tight_layout(pad=-5)

Я пытаюсь добавить небольшое пространство между красной и зеленой полосами выше. Спасибо. Вы видите сгенерированную фигуру: enter image description here

1 Ответ

2 голосов
/ 01 апреля 2020

Вы можете сделать некоторые ручные графики и выравнивания:

# set up figure
fig, ax = plt.subplots(figsize=(10,6))
y=np.arange(len(chart))

# height of bar and gap
height = 0.4
gap = 0.02

# plot with plt.barh
for offset, col in zip([-1,1], chart.columns):
    plt.barh(y + offset * (height+gap)/2, chart[col], height=height, label=col)

for p in ax.patches:
    v = ax.annotate("{:,.2%}".format(p.get_width()), (p.get_width(), p.get_y() + p.get_height()/4), xytext=(4, -1), 
                textcoords='offset points',ha='left');
plt.legend(loc='lower right',fontsize=10)
plt.tight_layout(pad=-5)

# invert the yaxis so you don't need [::-1]
ax.invert_yaxis()

# force yticks
plt.yticks(y, chart.index)
plt.show()

Вывод:

enter image description here

...