我有一个时间序列数据集,从1992-2017年。我可以为整个数据点设置颜色,但我想要的是为特定年份范围设置所需的颜色。例如;从1992 - 1995年的“蓝色”,从1995年到2005年的“红色”等。我们该怎么做?如何在一个图中为特定年份值范围指定不同的颜色? (Python)
数据集有2列;年和价值。
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)
欢迎SO。提供样本数据并告诉我们您做了什么:[最小,完整和可验证示例](https://stackoverflow.com/help/mcve) – skrubber
添加了代码和输出图片。 –