Home > Net >  How I can adjust properly the error bar in matplotlib?
How I can adjust properly the error bar in matplotlib?

Time:02-26

I need to fix an errorbar like in the graph, but I don't know how to use it. I get an error, and it doesn't work. Please can you help me?

#! /usr/bin/python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

x = np.arange(9)
country = [
    "Finland",
    "Denmark",
    "Switzerland",
    "Iceland",
    "Netherland",
    "Norway",
    "Sweden",
    "Luxembourg"
]
data = {
    "Explained by : Log GDP per Capita": [1.446, 1.502, 1.566, 1.482, 1.501, 1.543, 1.478, 1.751],
    "Explained by : Social Support": [1.106, 1.108, 1.079, 1.172, 1.079, 1.108, 1.062, 1.003],
    "Explained by : Healthy life expectancy": [0.741, 0.763, 0.816, 0.772, 0.753, 0.782, 0.763, 0.760],
    "Explained by : Freedom to make life choices": [0.691, 0.686, 0.653, 0.698, 0.647, 0.703, 0.685, 0.639],
    "Explained by : Generosity": [0.124, 0.208, 0.204, 0.293, 0.302, 0.249, 0.244, 0.166],
    "Explained by : Perceptions of corruption": [0.481, 0.485, 0.413, 0.170, 0.384, 0.427, 0.448, 0.353],
    "Dystopia   residual": [3.253, 2.868, 2.839, 2.967, 2.798, 2.580, 2.683, 2.653]
}
error_value = [[7.904, 7.780], [7.687, 7.552], [7.643, 7.500], [7.670, 7.438], [7.518, 7.410], [7.462, 7.323], [7.433, 7.293], [7.396, 7.252]]

df = pd.DataFrame(data, index=country)

df.plot(width=0.1, kind='barh', stacked=True, figsize=(11, 8))
plt.subplots_adjust(bottom=0.2)
# plt.errorbar(country, error_value, yerr=error_value)
plt.axvline(x=2.43, label="Dystopia (hapiness=2.43)")

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
           fancybox=True, shadow=True, ncol=3)
plt.xticks(x)
plt.show()

![Capture d’écran du 2022-02-25 11-06-56.png

CodePudding user response:

x = np.arange(9)
country = [
    "Finland"
]
data = {
    "Explained by : Log GDP per Capita": [1.446],
    "Explained by : Social Support": [1.106],
    "Explained by : Healthy life expectancy": [0.741],
    "Explained by : Freedom to make life choices": [0.691],
    "Explained by : Generosity": [0.124],
    "Explained by : Perceptions of corruption": [0.481],
    "Dystopia   residual": [3.253]
}

values = [1.446, 1.106, 0.741, 0.691, 0.124, 0.481, 3.253]
error_values = [(7.904-7.780)]

df = pd.DataFrame(data, index=country)

df.plot(width=0.1, kind='barh', stacked=True, figsize=(11, 8))
plt.subplots_adjust(bottom=0.2)
plt.errorbar(range(len(values)), values, xerr=error_values,
            fmt = 'none', capsize = 10, ecolor = 'red', elinewidth = 2, capthick = 8)
plt.axvline(x=2.43, label="Dystopia (hapiness=2.43)")

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
           fancybox=True, shadow=True, ncol=3)
plt.xticks(x)
plt.show()

Whitout error bar Whithout_Error_Bar

With the error bar With_Error_Bar

Excpected result

Expected_result

CodePudding user response:

enter image description here

  • Related