Matplotlib中为每个患者数据子列表的最后一个非NaN值位置绘制同色垂直虚线的实现方法
Matplotlib中为每个患者数据子列表的最后一个非NaN值位置绘制同色垂直虚线的实现方法
我来帮你搞定这个需求!你的代码已经完成了大部分基础工作,只需要补充绘制垂直虚线的逻辑就能达到目标效果。下面是调整后的完整代码,我会把关键改动点给你说明白:
首先,我们需要先定义一个全局的偏移量(你可以根据自己的图表需求调整数值),然后在遍历每个患者数据绘制曲线后,找到该患者最后一个非NaN值的x位置,再用和曲线相同的颜色绘制一条贯穿指定y范围的垂直虚线。
修改后的完整代码
import matplotlib.pyplot as plt import numpy as np def plot_app_efficiency(flat_list, D, P): if len(flat_list) % D != 0: raise ValueError("The length of the list must be a multiple of D.") # Split data for each patient patient_data = {} for idx, p_id in enumerate(P): start_idx = idx * D end_idx = (idx + 1) * D patient_data[p_id] = flat_list[start_idx:end_idx] # X-axis: days from 1 to D days = list(range(1, D + 1)) # Create plot fig, ax = plt.subplots(figsize=(10, 6)) # Calculate global y_min and y_max across all patients all_values = np.concatenate([np.array(values) for values in patient_data.values()]) y_min = np.nanmin(all_values) y_max = np.nanmax(all_values) # 定义y轴方向的偏移量,可根据需求调整 y_offset = 0.05 for patient, values in patient_data.items(): values = np.array(values) line, = ax.plot(days, values, label=f'Patient {patient}', marker='o') # Find the last valid (non-NaN) value valid_indices = np.where(~np.isnan(values))[0] if len(valid_indices) > 0: last_valid_index = valid_indices[-1] x_val = days[last_valid_index] # 获取当前患者曲线的颜色 line_color = line.get_color() # 绘制垂直虚线,y范围是全局y_min-offset到y_max+offset ax.vlines( x=x_val, ymin=y_min - y_offset, ymax=y_max + y_offset, color=line_color, linestyle='--', linewidth=1.5 ) # Axis labels and title ax.set_xlabel('Days (D)') ax.set_ylabel('Value') ax.set_title('Values per patient over days') # Remove grid ax.grid(False) # Horizontal legend below the plot ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), fancybox=True, shadow=False, ncol=len(P)) plt.tight_layout() plt.show() # Example Call a= [0.3, 0.3, 0.3, 0.3, 0.3, 0.3, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan] b=40 c=[1,2,3] plot_app_efficiency(a, b, c)
关键改动说明
- 新增了
y_offset变量,用来控制虚线超出全局y范围的距离,你可以根据图表的实际显示效果调整这个数值。 - 在找到每个患者的最后有效x位置后,通过
line.get_color()获取当前曲线的颜色,保证虚线和曲线同色。 - 使用
ax.vlines()函数绘制垂直虚线,这个函数可以直接指定x位置和y的上下范围,参数linestyle='--'设置为虚线样式,linewidth可以调整虚线的粗细。
这样运行代码后,每个患者的曲线末尾都会出现一条和曲线同色的垂直虚线,从全局最小值下方偏移一点的位置延伸到全局最大值上方偏移一点的位置,完全符合你的需求~
内容来源于stack exchange
相关产品推荐
相关产品推荐

