我正在为行星绘制right ascension ephemerides,它们具有周期性的属性:它们达到最大值24,然后从0开始。当我使用matplotlib绘制它们时,从24到零的“跳跃”连接在一起,这样我的水平线就会穿过我的身材:
如何消除这些线? matplotlib中是否有方法,或者可能是在跳转发生点之间拆分列表的方法。
生成上图的代码:
from __future__ import division
import ephem
import matplotlib
import matplotlib.pyplot
import math
fig, ax = matplotlib.pyplot.subplots()
ax.set(xlim=[0, 24])
ax.set(ylim=[min(date_range), max(date_range)])
ax.plot([12*ep.ra/math.pi for ep in [ephem.Jupiter(base_date + d) for d in date_range]], date_range,
ls='-', color='g', lw=2)
ax.plot([12*ep.ra/math.pi for ep in [ephem.Venus(base_date + d) for d in date_range]], date_range,
ls='-', color='r', lw=1)
ax.plot([12*ep.ra/math.pi for ep in [ephem.Sun(base_date + d) for d in date_range]], date_range,
ls='-', color='y', lw=3)
答案 0 :(得分:5)
这是一个生成器函数,用于查找“包装”数据的连续区域:
import numpy as np
def unlink_wrap(dat, lims=[-np.pi, np.pi], thresh = 0.95):
"""
Iterate over contiguous regions of `dat` (i.e. where it does not
jump from near one limit to the other).
This function returns an iterator object that yields slice
objects, which index the contiguous portions of `dat`.
This function implicitly assumes that all points in `dat` fall
within `lims`.
"""
jump = np.nonzero(np.abs(np.diff(dat)) > ((lims[1] - lims[0]) * thresh))[0]
lasti = 0
for ind in jump:
yield slice(lasti, ind + 1)
lasti = ind + 1
yield slice(lasti, len(dat))
示例用法是,
x = np.arange(0, 100, .1)
y = x.copy()
lims = [0, 24]
x = (x % lims[1])
fig, ax = matplotlib.pyplot.subplots()
for slc in unlink_wrap(x, lims):
ax.plot(x[slc], y[slc], 'b-', linewidth=2)
ax.plot(x, y, 'r-', zorder=-10)
ax.set_xlim(lims)
这给出了下图。请注意,蓝线(使用unlink_wrap
)被破坏,标准绘制的红线显示为参考。