Nikolaj
Nikolaj

Reputation: 1155

Matplotlib, draw on top

I am drawing an errorbar plot of some data points, and alongside these points, I want to draw the average in-between two values a line, I also want the line to be drawn on top of the errorbar.

In my code, I write the pyplot.errorbar(...) to draw the data points first, and then pyplot.plot(...) to draw the lines, and the result is that the errorbar is plotted on top of the lines, such that the line is hardly visible:

The orange line is hard to see

I have no idea as to how to draw the line on top, this is likely really easy to do, but I do not know how to do so.

Upvotes: 0

Views: 1714

Answers (2)

CypherX
CypherX

Reputation: 7353

You can also play with transparency (or opacity) by setting the parameter alpha in plt.errorbar() and the errorbar linewidth (elinewidth) to get a desirable effect.

Example with Dummy Data

import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline
%config InlineBackend.figure_format = 'svg' # 'svg', 'retina'
plt.style.use('seaborn-white')

# dummy data
np.random.seed(0)
x = np.arange(-1,1,0.1)
y, yerr = 2*np.random.randn(x.size) + 5, 1*np.random.randn(x.size)
xerr = 0.2*np.random.randn(x.size)

# make figure
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(16,6))
plt.sca(ax1)
plt.plot(x,y, 'bo', markersize=3)
plt.errorbar(x, y, xerr=xerr, 
            ecolor='red', elinewidth=1.2, barsabove=False, 
            alpha=0.3, lw=1)
plt.title('elinewidth = 1.2')
plt.sca(ax2)
plt.plot(x,y, 'bo', markersize=3)
plt.errorbar(x, y, xerr=xerr, 
            ecolor='red', elinewidth=2.0, barsabove=False, 
            alpha=0.3, lw=1)
plt.title('elinewidth = 2.0')
plt.suptitle('Controlling Errorbar Width and Transparency')
plt.show()

Output:
enter image description here

Upvotes: 0

mcsoini
mcsoini

Reputation: 6642

This is generally controlled using the zorder https://matplotlib.org/3.1.1/gallery/misc/zorder_demo.html

pyplot.plot([0,1], [0,1], linewidth=10)
pyplot.errorbar([0.5], [0.5], 0.3, 0.3, linewidth=20, zorder=-100)

enter image description here

pyplot.plot([0,1], [0,1], linewidth=10)
pyplot.errorbar([0.5], [0.5], 0.3, 0.3, linewidth=20, zorder=100)

enter image description here

Upvotes: 1

Related Questions