python 按日期更改线图颜色

ckx4rj1h  于 2023-05-27  发布在  Python
关注(0)|答案(2)|浏览(215)

我想绘制一个数据,其中x axis的日期时间值和另一组值为y。作为一个例子,我将使用matplotlib中的example,其中y是股票价格。下面是代码。

import matplotlib.pyplot as plt
from matplotlib.finance import quotes_historical_yahoo_ochl
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
import datetime
date1 = datetime.date(1995, 1, 1)
date2 = datetime.date(2004, 4, 12)

years = YearLocator()   # every year
months = MonthLocator()  # every month
yearsFmt = DateFormatter('%Y')

quotes = quotes_historical_yahoo_ochl('INTC', date1, date2)
if len(quotes) == 0:
    raise SystemExit

dates = [q[0] for q in quotes]
opens = [q[1] for q in quotes]

fig, ax = plt.subplots()
ax.plot_date(dates, opens, '-')

# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.autoscale_view()

# format the coords message box
def price(x):
   return '$%1.2f' % x
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.fmt_ydata = price
ax.grid(True)

fig.autofmt_xdate()
plt.show()

现在,我想做的是根据一些标准为图中的每个值着色。为了简单起见,假设示例中的标准基于年份。也就是说,属于同一年的价格将用相同的颜色表示。我该怎么做谢谢!

gpfsuwkq

gpfsuwkq1#

您可以使用numpy数组,并在您想要的范围内(在本例中为一年)使用掩码。为了使用示例中的内置YearLocator函数,您需要首先绘制图表并设置刻度,然后从示例中删除并替换为每年的范围。

import matplotlib.pyplot as plt
from matplotlib.finance import quotes_historical_yahoo_ochl
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
import datetime
import numpy 

date1 = datetime.date(1995, 1, 1)
date2 = datetime.date(2004, 4, 12)

years = YearLocator()   # every year
months = MonthLocator()  # every month
yearsFmt = DateFormatter('%Y')

quotes = quotes_historical_yahoo_ochl('INTC', date1, date2)
if len(quotes) == 0:
    raise SystemExit

dates = np.array([q[0] for q in quotes])
opens = np.array([q[1] for q in quotes])

fig, ax = plt.subplots()
l = ax.plot_date(dates, opens, '-')

# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.autoscale_view()

l[0].remove()
py = years()[0]
for year in years()[1:]:
    mask = (py < dates) & (dates < year)
    ax.plot_date(dates[mask], opens[mask], '-')
    py = year

# format the coords message box
def price(x):
   return '$%1.2f' % x
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.fmt_ydata = price
ax.grid(True)

fig.autofmt_xdate()
plt.show()

其给出,

s3fp2yjn

s3fp2yjn2#

我通常使用的方法是使用for循环绘制数据的不同部分,并在绘制时对每个部分进行着色。在您的示例中,此部分:

fig, ax = plt.subplots()
ax.plot_date(dates, opens, '-')

变成:

# import the colormaps
from maplotlib import cm

fig, ax = plt.subplots()

for y in years:
    y_indices = [i for i in range(len(dates)) if dates[i].year==y]

    # subset the data, there are better ways to do this
    sub_dates = [dates[i] for i in y_indices]
    sub_opens = [opens[i] for i in y_indices]

    # plot each section of data, using a colormap to change the color for
    # each iteration.
    ax.plot_date(sub_dates, sub_opens, '-', linecolor=cm.spring((y-2000)/10.0)

相关问题