Search code examples
pythonmatplotlibplotalphaalpha-transparency

Matplotlib: How to prevent transparent color overlay when curve overlaps?


For example we plot a line with transparent color here

import numpy as np
import matplotlib.pyplot as plt

a = np.array([1, 2, 3, 4, 5])
b = 2*a
plt.plot(a, b, 'blue', alpha=0.3)
plt.show()

enter image description here

but wenn I plot the same line multiple times, that overlaps with itself, so that the more it overlaps with itself, the darker it becomes.

import numpy as np
import matplotlib.pyplot as plt


a = np.array([1, 2, 3, 4, 5])
b = 2*a
for i in range(3):
    plt.plot(a, b, 'blue', alpha=0.3)
plt.show()

enter image description here

so How can I prevent the color-overlaps?

Thank you all in advance!

Update: Why I need this?

I am doing a Tolerance-Analysis. That means, the parameter change themselfs within a samll range and I will plot the curve for each change. Then I can find the worst case.

enter image description here

If I pick a solid but lighter color. It will looks like:

enter image description here

As you can see, with untransparent color I can not observe the node, which is covered by other line.

Update 2:

enter image description here


Solution

  • A single line does not overlay itself. Hence you can concatenate the multiple plots into a single one.

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    a = np.array([1, 2, 3, 4, 5])
    b = 2*a
    
    A = np.tile(np.append(a,[np.nan]),3)
    B = np.tile(np.append(b,[np.nan]),3)
    
    plt.plot(A, B, 'blue', alpha=0.3)
    plt.show()
    

    enter image description here

    This is essentially the inverse of this question How can I draw transparent lines where the color becomes stronger when they overlap?, where this effect was undesired.