matplotlib:如何从cdf图中删除datetime值的垂直线

时间:2018-06-05 11:08:37

标签: python matplotlib cdf

以下代码为日期时间值绘制cdf:

import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np; np.random.seed(42)
import pandas as pd

objDate = dates.num2date(np.random.normal(735700, 300, 700))

ser = pd.Series(objDate)
ax = ser.hist(cumulative=True, density=1, bins=500, histtype='step')

plt.show()

cdf of datetime values

如何删除图表最右端的垂直线?提及here的方法不能用#9替换第9行。

ax = ser.hist(cumulative=True, density=1, bins=sorted(objDate)+[np.inf], histtype='step')

给出

  

TypeError:无法将datetime.datetime与float

进行比较

1 个答案:

答案 0 :(得分:1)

CDF实际上绘制为多边形,matplotlib中的多边形由路径定义。路径又由顶点(去哪里)和代码(如何到达)定义。文档说我们不应该直接改变这些属性,但我们可以创建一个符合我们需要的旧的 new 多边形。

poly = ax.findobj(plt.Polygon)[0]
vertices = poly.get_path().vertices

# Keep everything above y == 0. You can define this mask however
# you need, if you want to be more careful in your selection.
keep = vertices[:, 1] > 0

# Construct new polygon from these "good" vertices
new_poly = plt.Polygon(vertices[keep], closed=False, fill=False,
                       edgecolor=poly.get_edgecolor(),
                       linewidth=poly.get_linewidth())
poly.set_visible(False)
ax.add_artist(new_poly)
plt.draw()

你应该得到如下图所示的内容:

CDF with offending points removed