通过在开头添加 0 并在最后添加一个变量值来重新排列步骤图

Rearrange the step chart by adding 0 to the beginning and a variable value to the last

我正在 Python 使用 Tkinter、ElementTree、Numpy、Pandas 和 Matplotlib 模块开发这个项目:

    # Function to extract the Name and Value attributes
    def extract_name_value(signals_df, rootXML):
        # print(signals_df)
        names_list = [name for name in signals_df['Name'].unique()]
        num_names_list = len(names_list)
        num_axisx = len(signals_df["Name"])
        values_list = [value for pos, value in enumerate(signals_df["Value"])]
        print(values_list)
        points_axisy = signals_df["Value"]
        print(len(points_axisy))
    
        colors = ['b', 'g', 'r', 'c', 'm', 'y']
    
        # Creation Graphic
        fig, ax = plt.subplots(nrows=num_names_list, figsize=(20, 30), sharex=True)
        plt.suptitle(f'File XML: {rootXML}', fontsize=16, fontweight='bold', color='SteelBlue', position=(0.75, 0.95))
        plt.xticks(np.arange(-1, num_axisx), color='SteelBlue', fontweight='bold')
        i = 1
        for pos, name in enumerate(names_list):
            # get data
            data = signals_df[signals_df["Name"] == name]["Value"]
            print(data)
            # get color
            j = random.randint(0, len(colors) - 1)
            # get plots by index = pos
            ax[pos].plot(data.index, data, drawstyle='steps-post', marker='o', color=colors[j], linewidth=3)
            ax[pos].set_ylabel(name, fontsize=8, fontweight='bold', color='SteelBlue', rotation=30, labelpad=35)
            ax[pos].yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
            ax[pos].yaxis.set_tick_params(labelsize=6)
            ax[pos].grid(alpha=0.4)
            i += 1
    
        # plt.show()
    

但我想在所有子图 () 情况下使 y 轴值从 0 开始,并以 points_axisy 变量的大小或长度结束,并像我分享的图表中那样绘制它以下:

也就是说,徒手画的黄色线被图形的值代替了,但我不知道该怎么做。我已经在使用枚举函数测试代码,但找不到解决方案。用于测试我的代码的 xml 文件可以取自:xml file 非常感谢您的帮助,任何评论都有帮助。

基于黄色标记:

  1. x应该向左扩展到-1,向右扩展到27(len(signals_df) - 1)
  2. y左边应该是0,右边继续data的最后一个值(data.iloc[-1])

您可以 prepend/append 这些值作为 numpy 数组使用 hstack():

x = np.hstack([-1, data.index.values, len(signals_df) - 1])
y = np.hstack([0, data.values, data.iloc[-1]])
ax[pos].plot(x, y, drawstyle='steps-post', marker='o', color=colors[j], linewidth=3)

或作为列表:

x = [-1] + data.index.tolist() + [len(signals_df) - 1]
y = [0] + data.tolist() + [data.iloc[-1]]
ax[pos].plot(x, y, drawstyle='steps-post', marker='o', color=colors[j], linewidth=3)