The smallest valid alpha value in matplotlib?

Question:

Some of my plots have several million lines. I dynamically adjust the alpha value, by the number of lines, so that the outliers more or less disappear, while the most prominent features appear clear. But for some alpha‘s, the lines just disappear.

What is the smallest valid alpha value for line plots in in matplotlib? And why is there a lower limit?

Answers:

There’s no lower limit; the lines just appear to be invisible for very small alpha values.

If you draw one line with alpha=0.01 the difference in color is too small for your screen / eyes to discern. If you draw 100 lines with a=0.01 on top of each other, you will see them.

As for your problem, you can just add a small number to the alpha value of each draw call so that lines that would otherwise have alpha < 0.1 still appear.

Answered By: Mario H

As @ImportanceOfBeingErnest suggested in the comments, the lower limit seems to be 1/255.

I did not have time to go though the source code and all, but I did test it, and assume what happens is, that the input alpha value needs to be represented as an int between 0 and 255:

int(alpha*255)

When the input alpha value is smaller than 1/255, e.g. 1/256, it is therefore represented by a 0, and the plot lines disappear. Whereas when the alpha is 1/255 (or slightly larger), it is converted to 1, and the plot lines can be seen.

Answered By: Hallgeir Wilhelmsen

My guess would also have been 1./255 such that the maximum 8-bit RGB color multiplied with alpha still makes a non-zero contribution to the image. However, that would also only allow to draw lines with fully saturated colors, and in reality it is not true.

Changing the relevant value in

for i in range(1000):
    plt.plot((0, 100), (0, 100), alpha = 1/510, color = "g") 

I found that the limit is actually 510 (i.e., the minimum alpha is 1./510). This holds true also for non-saturated colors (e.g., "wheat"), so reality is obviously still more complicated than the naive assumption described above.
My matplotlib version is 3.4.2.

I haven’t investigated this further — for very large numbers of overlaid images one would have to come up with a different approach anyway. There is a related ticket on github that suggests using mplcairo. Another option would be to export the output images as numpy arrays so that one can manually add and normalize them.

Answered By: fuenfundachtzig
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.