简体   繁体   中英

Scale errorbar transparency with the size in matplotlib

I have quite a messy plot and so, in order to tidy it up, I want to make those points with larger error bars less significant by reducing their alpha value. Preferably, I'd like to map a continuous scale of alpha values (like a colourmap) to each point and its errorbar according to their errorbar size - I'm not too sure what the best/efficient way to go about doing this would be.

You can certainly set the alpha of the errorbars, but I think you need to plot each one separately because Matplotlib won't set the opacity (or color) of the vertical lines and caplines to a sequence (as far as I know).

If you want the markers to have their opacity matching the errorbars, its probably easier to build a sequence of colors based on some normalization:

import numpy as np
import matplotlib.pyplot as plt

n = 20
x = np.linspace(1, 10, n)
y = x - x**2
minerr = 2
yerr = abs(np.random.randn(n) * 15) + minerr
maxerr = max(yerr)
err_range = maxerr - minerr

alphas = [1 - (err-minerr)/(err_range) for err in yerr]
colors = np.asarray([(1,0,0, alpha) for alpha in alphas])

plt.scatter(x,y, c=colors, edgecolors=colors)
for pos, ypt, err, color in zip(x, y, yerr, colors):
    plotline, caplines, (barlinecols,) = plt.errorbar(pos, ypt, err, lw=2, color=color, capsize=5, capthick=2)

plt.xlim(0,11)
plt.show()

在此输入图像描述

However, you might want to think about whether the effect you create might misrepresent your data (ie make it look more accurate than it is by emphasizing only the points with small error bars).

You can set a colour as the third variable on a scatter graph (see this answer ). To change alpha, you could change only the fourth value (transparency) in color based on the scaled range. As a minimal example,

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 100)
y = np.sin(x)
z = x + 20 * y

scaled_z = (z - z.min()) / z.ptp()
colors = [[0., 0., 0., i] for i in scaled_z]

plt.scatter(x, y, marker='x', edgecolors=colors, s=150, linewidths=4)
plt.show()

Which looks like 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM