如何删除 Matplotlib 中的空 x 轴坐标

How to remove empty x-axis coordinates in Matplotlib

我在 Python 中使用 pandas、numpy 和 matplotlib 模块进行开发,使用以下代码绘制数据帧的各种子图:

    import pandas as pd
    import numpy as np
    from matplotlib import pyplot as plt
    import matplotlib.ticker as ticker
    
    data = {'Name': ['Status', 'Status', 'HMI', 'Allst', 'Drvr', 'CurrTUBand', 'RUSource', 'RUReqstrPriority', 'RUReqstrSystem', 'RUResReqstStat', 'CurrTUBand', 'DSP', 'SetDSP', 'SetDSP', 'DSP', 'RUSource', 'RUReqstrPriority', 'RUReqstrSystem', 'RUResReqstStat', 'Status', 'Delay', 'Status', 'Delay', 'HMI', 'Status', 'Status', 'HMI', 'DSP'],
            'Value': [4, 4, 2, 1, 1, 1, 0, 7, 0, 4, 1, 1, 3, 0, 3, 0, 7, 0, 4, 1, 0, 1, 0, 1, 4, 4, 2, 3],
            'Id_Par': [0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 0, 0, 22, 22, 28, 28, 28, 28, 0, 0, 38, 38, 0, 0, 0, 0, 0]
    }
    
    signals_df = pd.DataFrame(data)
    
    
    def plot_signals(signals_df):
        # Count signals by parallel
        signals_df['Count'] = signals_df.groupby('Id_Par').cumcount().add(1).mask(signals_df['Id_Par'].eq(0), 0)
        # Subtract Parallel values from the index column
        signals_df['Sub'] = signals_df.index - signals_df['Count']
        id_par_prev = signals_df['Id_Par'].unique()
        id_par = np.delete(id_par_prev, 0)
        signals_df['Prev'] = [1 if x in id_par else 0 for x in signals_df['Id_Par']]
        signals_df['Final'] = signals_df['Prev'] + signals_df['Sub']
        # Convert and set Subtract to index
        signals_df.set_index('Final', inplace=True)
    
        # Get individual names and variables for the chart
        names_list = [name for name in signals_df['Name'].unique()]
        num_names_list = len(names_list)
    
        # Creation Graphics
        fig, ax = plt.subplots(nrows=num_names_list, figsize=(10, 10), sharex=True)
        plt.xticks(color='SteelBlue', fontweight='bold')
    
        # Matplotlib's categorical feature to convert x-axis values to string
        x_values = [-1, ]
        for name in all_names_list:
            x_values.append(signals_df[signals_df["Name"] == name]["Value"].index.values[0])
        x_values.append(len(signals_df) - 1)
        x_values = [str(i) for i in sorted(set(x_values))]
        print(x_values)
    
        for pos, (a_, name) in enumerate(zip(ax, names_list)):
            # Creating a dummy plot and then remove it
            dummy, = ax[pos].plot(x_values, np.zeros_like(x_values))
            dummy.remove()
            # Get data
            data = signals_df[signals_df["Name"] == name]["Value"]
            # Get values axis-x and axis-y
            x_ = np.hstack([-1, data.index.values, len(signals_df) - 1])
            y_ = np.hstack([0, data.values, data.iloc[-1]])
            # Plotting the data by position
            ax[pos].plot(x_.astype('str'), y_, drawstyle='steps-post', marker='*', markersize=8, color='k', linewidth=2)
            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, color='SteelBlue')
            # Labeling the markers with CAN-Values
            for i in range(len(y_)):
                if i == 0:
                    xy = [x_[0].astype('str'), y_[0]]
                else:
                    xy = [x_[i - 1].astype('str'), y_[i - 1]]
                ax[pos].text(x=xy[0], y=xy[1], s=str(xy[1]), color='k', fontweight='bold', fontsize=12)
        plt.show()
    
    
    plot_signals(signals_df)

当名称重复时我遇到了麻烦,使用 Matplotlib 的分类特征并将 x 轴值转换为字符串; ;这就是给我带来的:

我一直在尝试更改 pandas 条件,因为这是我在这一行中使用的条件:x_values.append(signals_df[signals_df["Name"] == name]["Value"].index.values[0]) 并且当我打印变量 x_values 时它带来我输入了错误的索引:['-1', '0', '2', '3', '4', '5', '6', '11', '12', '20', '27'],我无法让它正常工作。 我希望实现如下图:

黄色阴影是它必须在 x 轴上进行的跳跃,而不是在 y 轴上绘制。非常感谢任何可以帮助我的人,任何评论都有帮助。

我将此答案留待以后搜索具有相同主题的人时使用。我发现我的错误,我处理for循环的方式不正确,我替换它并修改如下:

    # Matplotlib's categorical feature and to convert x-axis values to string
    x_values = [-1,]
    x_values + = (list (set (can_signals.index)))
    x_values = [str (i) for i in sorted (x_values)]

现在可以显示如下图表: