Python Matplotlib : Changing color in plot_date

标签 python matplotlib

我想绘制一个数据,其中 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()

这给出了,

enter image description here

关于Python Matplotlib : Changing color in plot_date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360979/

相关文章:

python - 读取彩色数字图像是什么数字以进行控制台

python - 插值忽略数组中的零值 - Python

python - 我有 8 年的每日数据。我想绘制一周中每天、一年中的每周和一年中的每个月的所有值。我怎么做?

python - 绘制颜色条时强制方形子图

matplotlib - 如何增加gnuplot中的颜色数量?

javascript - 是否有 JavaScript 或可能的 Python/Django Web 服务来对街道地址进行地理编码?

python - Pandas 使用外部变量应用函数

python - 从列表python中找到最大平均值

python - 从远程机器上的 docker 容器上执行命令

python - 如何在 matplotlib 中为一个图形设置本地 rcParams 或 rcParams