How to generate random colors in matplotlib?

前端 未结 11 2227
长情又很酷
长情又很酷 2020-12-12 16:13

What\'s the trivial example of how to generate random colors for passing to plotting functions?

I\'m calling scatter inside a loop and want each plot a different col

11条回答
  •  情歌与酒
    2020-12-12 16:18

    Since the question is How to generate random colors in matplotlib? and as I was searching for an answer concerning pie plots, I think it is worth to put an answer here (for pies)

    import numpy as np
    from random import sample
    import matplotlib.pyplot as plt
    import matplotlib.colors as pltc
    all_colors = [k for k,v in pltc.cnames.items()]
    
    fracs = np.array([600, 179, 154, 139, 126, 1185])
    labels = ["label1", "label2", "label3", "label4", "label5", "label6"]
    explode = ((fracs == max(fracs)).astype(int) / 20).tolist()
    
    for val in range(2):
        colors = sample(all_colors, len(fracs))
        plt.figure(figsize=(8,8))
        plt.pie(fracs, labels=labels, autopct='%1.1f%%', 
                shadow=True, explode=explode, colors=colors)
        plt.legend(labels, loc=(1.05, 0.7), shadow=True)
        plt.show()
    

    Output

提交回复
热议问题