How to specify different color for a specific year value range in a single figure? (Python)

后端 未结 2 1373
無奈伤痛
無奈伤痛 2020-12-18 17:14

I\'ve a time-series dataset, from 1992-2017. I can set a color for the whole data dots but what I want is to set desired color for specific year range. For Example; from 199

2条回答
  •  醉酒成梦
    2020-12-18 17:22

    I made my own random data for this function to work but assuming you have non-overlapping date ranges, this should work. It also seemed like your dates are not of pd.datetime type. This should work for pd.datetime types but your lookup values in the dictionary will be something like ("1992-01-01","2000-01-01") and so on.

    # Create data
    data = np.random.rand(260,1)
    dates = np.array(list(range(1992,2018))*10)
    
    df = pd.DataFrame({"y":data[:,0],"date":dates})
    df = df.sort(columns="date")
    
    # Dictionary lookup
    lookup_dict = {(1992,2000):"r", (2001,2006):"b",(2007,2018):"k"}
    
    # Slice data and plot
    fig, ax = plt.subplots()
    for lrange in lookup_dict:
        temp = df[(df.date>=lrange[0]) & (df.date<=lrange[1])]
        ax.plot(temp.date,temp.y,color=lookup_dict[lrange], marker="o",ls="none")
    

    This produces:

提交回复
热议问题