Matplotlib scatterplot; colour as a function of a third variable

前端 未结 3 1089
遥遥无期
遥遥无期 2020-11-22 11:57

I want to make a scatterplot (using matplotlib) where the points are shaded according to a third variable. I\'ve got very close with this:

plt.scatter(w, M,          


        
3条回答
  •  轮回少年
    2020-11-22 12:47

    Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

    • Plot points corresponding to Physical variable 'A' in RED.
    • Plot points corresponding to Physical variable 'B' in BLUE.
    • Plot points corresponding to Physical variable 'C' in GREEN.

    In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

    x=['A','B','B','C','A','B']
    y=[15,30,25,18,22,13]
    
    # Function to map the colors as a list from the input list of x variables
    def pltcolor(lst):
        cols=[]
        for l in lst:
            if l=='A':
                cols.append('red')
            elif l=='B':
                cols.append('blue')
            else:
                cols.append('green')
        return cols
    # Create the colors list using the function above
    cols=pltcolor(x)
    
    plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
    plt.grid(True)
    plt.show()
    

提交回复
热议问题