Skip to main content
 首页 » 编程设计

Python Matplotlib : Changing color in plot_date

2025年05月04日24webabcd

我想绘制一个数据,其中 x 轴 具有日期时间值,另一组值作为 y。作为示例,我将使用 example来自 matplotlib,其中 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() 

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

请您参考如下方法:

您可以在您想要的范围内(在本例中为一年)使用带有掩码的 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() 

这给出了,