How do I set color to Rectangle in Matplotlib?

前端 未结 3 946
广开言路
广开言路 2021-02-02 10:35

How do I set color to Rectangle for example in matplotlib? I tried using argument color, but had no success.

I have following code:

fig=pylab.figure()
ax         


        
3条回答
  •  灰色年华
    2021-02-02 11:22

    To avoid calling .add_patch() multiple times (often the purpose of using PatchCollection in the first place), you can pass a ListedColormap to the PatchCollection via cmap=.

    This looks as follows (modified from fraxel's answer):

    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    from matplotlib.collections import PatchCollection
    import numpy as np
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    patches_list = []
    color_list = []
    patches_list.append(matplotlib.patches.Rectangle((-200,-100), 400, 200))
    color_list.append('yellow')
    patches_list.append(matplotlib.patches.Rectangle((0,150), 300, 20))
    color_list.append('red')
    patches_list.append(matplotlib.patches.Rectangle((-300,-50), 40, 200))
    color_list.append('#0099FF')
    patches_list.append(matplotlib.patches.Circle((-200,-250), radius=90))
    color_list.append('#EB70AA')
    
    our_cmap = ListedColormap(color_list)
    patches_collection = PatchCollection(patches_list, cmap=our_cmap)
    patches_collection.set_array(np.arange(len(patches_list)))
    ax.add_collection(patches_collection)
    
    plt.xlim([-400, 400])
    plt.ylim([-400, 400])
    plt.show()
    

    Result: cmap_approach_result

提交回复
热议问题