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

徘徊边缘 提交于 2019-11-29 09:00:28

I could imagine that using a colormap for a scatter plot of the points may be an easy solution. The scatter's color would then simply be defined by the year, assuming the year is given in decimal format. A BoundaryNorm would define the ranges for the values and a colormap can easily be created from a list of colors.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors

y =  np.random.rand(300)*26+1992
d = (3.075*(y-1992)-17)+np.random.normal(0,5,300)
df = pd.DataFrame({"year" : y, "data" : d})

bounds = [1992,1995,2005,2015,2018]
colors = ["darkorchid", "crimson", "limegreen", "gold"]
cmap = matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.BoundaryNorm(bounds, len(colors))

fig, ax = plt.subplots()
sc = ax.scatter(df.year, df.data, c=df.year.values, cmap=cmap, norm=norm)
fig.colorbar(sc, spacing="proportional")

fit = np.polyfit(df.year.values, df.data.values, deg=1)
ax.plot(df.year, np.poly1d(fit)(df.year.values), color="k")

plt.show()

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!