How to pick a new color for each plotted line within a figure in matplotlib?

前端 未结 7 699
日久生厌
日久生厌 2020-11-27 11:06

I\'d like to NOT specify a color for each plotted line, and have each line get a distinct color. But if I run:

from matplotlib import pyplot as plt
for i in          


        
7条回答
  •  离开以前
    2020-11-27 11:39

    As Ciro's answer notes, you can use prop_cycle to set a list of colors for matplotlib to cycle through. But how many colors? What if you want to use the same color cycle for lots of plots, with different numbers of lines?

    One tactic would be to use a formula like the one from https://gamedev.stackexchange.com/a/46469/22397, to generate an infinite sequence of colors where each color tries to be significantly different from all those that preceded it.

    Unfortunately, prop_cycle won't accept infinite sequences - it will hang forever if you pass it one. But we can take, say, the first 1000 colors generated from such a sequence, and set it as the color cycle. That way, for plots with any sane number of lines, you should get distinguishable colors.

    Example:

    from matplotlib import pyplot as plt
    from matplotlib.colors import hsv_to_rgb
    from cycler import cycler
    
    # 1000 distinct colors:
    colors = [hsv_to_rgb([(i * 0.618033988749895) % 1.0, 1, 1])
              for i in range(1000)]
    plt.rc('axes', prop_cycle=(cycler('color', colors)))
    
    for i in range(20):
        plt.plot([1, 0], [i, i])
    
    plt.show()
    

    Output:

    Now, all the colors are different - although I admit that I struggle to distinguish a few of them!

提交回复
热议问题