При попытке построить следующий код я получил 4 графика, но процент отображается только на последнем графике.
fig, axes =plt.subplots(12,2,figsize=(12,50))
plt.subplots_adjust(wspace=0.9, hspace=0.9)
i=0
total = len(data['work_year'])
for fea_name in fea:
ax= axes[i//2, i%2]
i += 1
sns.countplot(x=fea_name, data=data, ax=ax,palette='icefire' )
ax.set_title(f'Countplot of {fea_name}')
for i in range(len(fea), 12 * 2):
fig.delaxes(axes[i//2, i%2])
for p in ax.patches:
percentage = '{:.1f}%'.format(100 * p.get_height() / total)
x = p.get_x() + p.get_width()/3
y = p.get_y() + p.get_height()+50
ax.annotate(percentage, (x, y))
plt.tight_layout()
plt.show()
Показаны проценты только на одном графике
fig, axes =plt.subplots(12,2,figsize=(12,50))
plt.subplots_adjust(wspace=0.9, hspace=0.9)
i=0
total = len(data['work_year'])
for fea_name in fea:
ax= axes[i//2, i%2]
i += 1
sns.countplot(x=fea_name, data=data, ax=ax,palette='icefire' )
ax.set_title(f'Countplot of {fea_name}')
# ax.tick_params(axis='x', rotation=45)
for i in range(len(fea), 12 * 2):
fig.delaxes(axes[i//2, i%2])
for ax in axes.flat:
for p in ax.patches:
percentage = '{:.1f}%'.format(100 * p.get_height() / total)
x = p.get_x() + p.get_width()/3
y = p.get_y() + p.get_height()+50
ax.annotate(percentage, (x, y))
plt.tight_layout()
plt.show()
Как сейчас написано, ваш ответ неясен. Пожалуйста, отредактируйте , чтобы добавить дополнительную информацию, которая поможет другим понять, как это относится к заданному вопросу. Более подробную информацию о том, как писать хорошие ответы, вы можете найти в справочном центре.
Вы можете немного упростить свой код с помощью ax.bar_label()
.
(Последняя версия Seaborn требует, чтобы hue=
был равен столбцу x=
при использовании палитры.)
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# first, create some reproducible test data
data = pd.DataFrame({'feature1': np.random.choice([*'abc'], 200),
'feature2': np.random.choice([*'defg'], 200),
'feature3': np.random.choice([*'hij'], 200),
'feature4': np.random.choice([*'klmno'], 200)})
fea = ['feature1', 'feature2', 'feature3', 'feature4']
fig, axes = plt.subplots(2, 2, figsize=(12, 12))
total = len(data)
for fea_name, ax in zip(fea, axes.flat):
sns.countplot(x=fea_name, data=data, ax=ax, hue=fea_name, palette='icefire')
ax.set_title(f'Countplot of {fea_name}')
for c in ax.containers:
ax.bar_label(c, fmt=lambda x: f'{x / total:.1%}')
plt.tight_layout()
plt.show()
Когда я попытался запустить этот код, он показал мне ошибку «неподдерживаемый тип(ы) операнда для%: «функция» и «float».
Я тестировал seaborn 0.13.2 и matplotlib 3.8.3.
Перед строкой
for p in ax.patches:
ты забылfor ax in axes.flat:
.