Skip to main content
 首页 » 编程设计

python之matplotlib:如何从日期时间值的 cdf 图中删除垂直线

2024年12月31日11yjmyzz

以下代码绘制日期时间值的 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() 

如何去掉图表最右端的竖线?提到的方法here不能将第 9 行替换为:

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

给予

TypeError: can't compare datetime.datetime to float

请您参考如下方法:

CDF 实际上绘制为多边形,在 matplotlib 中由路径 定义。路径又由顶点(去哪里)和代码(如何到达那里)定义。文档说我们不应该直接改变这些属性,但我们可以从旧多边形派生出满足我们需要的新多边形。

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() 

你应该得到如下图所示的结果: