nj2237
nj2237

Reputation: 1278

How to add error values next to error bars?

I'm using matplotlib for my plots. I have with me the plot and errorbar. I want to specify the error value in text next to the errorbars. I'm looking for something like this (edited in pinta):

enter image description here

Is this possible to do in this code:


import numpy as np
import matplotlib.pyplot as plt
import math

N = 8

y1 = [0.1532, 0.1861, 0.2618, 0.0584, 0.1839, 0.2049, 0.009, 0.2077]
y1err = []

for item in y1:
    err = 1.96*(math.sqrt(item*(1-item)/10000))
    y1err.append(err)

ind = np.arange(N)
width = 0.35

fig, ax = plt.subplots()

ax.bar(ind, y1, width, yerr=y1err, capsize=7)

ax.grid()
plt.show()

Upvotes: 5

Views: 1085

Answers (1)

Diego Palacios
Diego Palacios

Reputation: 1144

You can use the annotate function to add text labels in the plot. Here is how you could do it:

import numpy as np
import matplotlib.pyplot as plt
import math

N = 8

y1 = [0.1532, 0.1861, 0.2618, 0.0584, 0.1839, 0.2049, 0.009, 0.2077]
y1err = []

for item in y1:
    err = 1.96*(math.sqrt(item*(1-item)/10000))
    y1err.append(err)

ind = np.arange(N)
width = 0.35

fig, ax = plt.subplots()

ax.bar(ind, y1, width, yerr=y1err, capsize=7)

# add error values
for k, x in enumerate(ind):
    y = y1[k] + y1err[k]
    r = y1err[k] / y1[k] * 100
    ax.annotate(f'{y1[k]:.2f} +/- {r:.2f}%', (x, y), textcoords='offset points',
                xytext=(0, 3), ha='center', va='bottom', fontsize='x-small')

ax.grid()
plt.show()

Upvotes: 5

Related Questions