Я пытаюсь создать гистограмму ошибок с помощью Matplotlib, где мне нужно обеспечить определенный порядок категориальных переменных на оси Y. Несмотря на установку порядка категорий и сортировку DataFrame, график не отражает желаемый порядок.
Вот упрощенная версия моего кода:
import pandas as pd
import matplotlib.pyplot as plt
# Data for ITT
itt_data = {
'Variable': ['Most Similar', 'Moderately Similar', 'Distinct', 'Most Distinct'],
'Coef.': [0.2572047, 0.1326441, 0.4539544, -0.7915292],
'Std. Err.': [0.3592403, 0.3272935, 0.3179865, 0.3443217],
'0.025': [-0.4471788, -0.5090995, -0.1695404, -1.466661],
'0.975': [0.9615881, 0.7743876, 1.077449, -0.1163975]
}
itt_df = pd.DataFrame(itt_data)
# Set the order of the 'Variable' column
order = ['Most Similar', 'Moderately Similar', 'Distinct', 'Most Distinct']
itt_df['Variable'] = pd.Categorical(itt_df['Variable'], categories=order, ordered=True)
itt_df = itt_df.sort_values('Variable')
# Plotting function for ITT
def plot_itt_coefficients(data, title, color, filename):
fig, ax = plt.subplots(figsize=(4, 8)) # Different size for ITT plot
# Reorder the data according to the specified order
data = data.set_index('Variable').reindex(order)
# Ensure the variables are plotted in the correct order
variables = data.index.tolist()
coefficients = data['Coef.'].tolist()
errors_low = (data['Coef.'] - data['0.025']).tolist()
errors_high = (data['0.975'] - data['Coef.']).tolist()
errors = [errors_low, errors_high]
ax.errorbar(coefficients, range(len(variables)), xerr=errors, fmt='o', capsize=3, elinewidth=1.5, color=color)
ax.axvline(x=0, color='black', linestyle='--')
ax.set_xlim(-3, 3)
ax.set_yticks(range(len(variables)))
ax.set_yticklabels(variables)
ax.set_xlabel('Point Estimate')
ax.set_ylabel('')
ax.set_title(title)
plt.tight_layout()
plt.savefig(filename) # Save the figure
plt.show()
# Colors from the screenshot
colors = ['#b5d1ae', '#80ae9a', '#568b87', '#326b77', '#1b485e', '#122740']
# Plot ITT Results
plot_itt_coefficients(itt_df, 'ITT', colors[0], 'ITT_Results.png')
Подробнее здесь: https://stackoverflow.com/questions/788 ... rorbar-plo
Как обеспечить определенный порядок категориальных переменных в графике панели ошибок Matplotlib (ось Y) ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
HistGradientBoostingClassifier с использованием категориальных переменных
Anonymous » » в форуме Python - 0 Ответы
- 4 Просмотры
-
Последнее сообщение Anonymous
-
-
-
HistGradientBoostingClassifier с использованием категориальных переменных
Anonymous » » в форуме Python - 0 Ответы
- 8 Просмотры
-
Последнее сообщение Anonymous
-