Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

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

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 1992-1995 "Blue", from 1995-2005 "Red" etc. How can we do that?

Dataset has 2 columns; year and value.

import numpy as np
import pandas as pd
from scipy import stats
from sklearn import linear_model
from matplotlib import pyplot as plt
import pylab
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression

Atlantic = pd.read_csv('C:\AtlanticEnd.csv', error_bad_lines=False)

X = Atlantic['year']

y = Atlantic['Poseidon']

plt.figure(figsize=(20,10))
plt.ylabel('Change in mean sea level [mm]', fontsize=20)
plt.xlabel('Years', fontsize=20)
plt.title('Atlantic Ocean - Mean Sea Level', fontsize=20)
colors = ["blue", "red", "green", "purple"]
texts = ["Poseidon", "Jason1", "Jason2", "Jason3"]
patches = [ plt.plot([],[], marker="o", ms=10, ls="", mec=None, color=colors[i], 
            label="{:s}".format(texts[i]) )[0]  for i in range(len(texts)) ]
plt.legend(handles=patches, loc='upper left', ncol=1, facecolor="grey", numpoints=1 )

plt.plot(X, y, 'ro', color='red')

slope, intercept, r_value, p_value, std_err = stats.linregress(X, y)
plt.plot(X, X*slope+intercept, 'b')

plt.axis([1992, 2018, -25, 80])

plt.grid(True)

plt.show()

def trendline(Atlantic, order=1):
    coeffs = np.polyfit(Atlantic.index.values, list(Atlantic), order)
    slope = coeffs[-2]
    return float(slope)

slope = trendline(y)
print(slope)

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...