首页 > 解决方案 > Matplotlib 在子图中绘制多列

问题描述

我正在尝试将 CSV 文件中的多列绘制到一个 DataFrame 上,类似于这张,只是它将用于多个子图。

这是代码:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.cbook as cbook

root = Tk()
plt.style.use('bmh')

def preview_latest_force():

    ylabel_counter = 0
    ylabel_text = 'Sensor'
    ylabel_counter_str = ''
    positions = (0, 40, 80)
    labels = ("0", "40", "80")
    df = pd.read_csv(root.filename)
    y = df['Total Data']
    x = df['Time Stamp']
    s_one = df['Data 1']
    s_two = df['Data 2']
    data_angle = df['Bend Angle']
    marker_stamp = df['Marker Stamp']

    df = pd.read_csv(root.filename)
    y = df['Total Data']
    x = df['Time Stamp']
    s_one = df['Data 1']
    s_two = df['Data 2']
    data_angle = df['Bend Angle']
    marker_stamp = df['Marker Stamp']

    def format_axes(fig):
        for i, ax in enumerate(fig.axes):
            print("Axes:", i)
            if i == 0:                                                                                  
                ax.set(xlabel='', ylabel='All Data')
            elif i == 1:                                               
                ax.tick_params(labelbottom=True)
                ax.set(xlabel='Time (s)', ylabel='Data Angle')
            elif i != 5:                                           
                ax.tick_params(labelbottom=True, labelleft=True)
                ax.set_ylabel("%d" % (i), rotation='horizontal') 
                ax.yaxis.set_label_coords(-0.09, 0.1)
            else:                                        
                ax.tick_params(labelbottom=True, labelleft=True)
                ax.set(xlabel='Time (s)')
                ax.set_ylabel("%d" % (i), rotation='horizontal') 
                ax.yaxis.set_label_coords(-0.09, 0.1)
                
    # gridspec inside gridspec
    w = 16 
    h = 9
    d = 200

    fig = plt.figure(figsize=(w, h), tight_layout = True)
    fig.subplots_adjust(hspace=0.5, wspace=0)

    #Generating "master subplots" 
    gs0 = gridspec.GridSpec(1, 2, figure=fig)

    #Ploting right side subplots
    gs00 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs0[1], hspace=0)

    ax0 = fig.add_subplot(gs00[0 , :])
    ax0.plot(x, y)

    ax01 = fig.add_subplot(gs00[1 , :])
    ax01.plot(x, data_angle)

    #Ploting left side subplots
    gs01 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs0[0], hspace=0)

    ax12 = fig.add_subplot(gs01[0, :])
    ax12.plot(x, s_one)
    plt.yticks(positions, labels)

    ax13 = fig.add_subplot(gs01[1, :])
    ax13.plot(x, s_two)
    plt.yticks(positions, labels)

    plt.suptitle('Data Against Time')

    format_axes(fig)
        
    plt.show()
    plt.savefig("out.png")


preview_latest_force()

root.mainloop()

本质上,对于marker_stamp数据,我希望以点图格式将其绘制在其他数据帧之上,如下图所示,假设数据marker_stampTime = 20s, Value = 40在此处输入图像描述

我可以检查在子图中绘制列的语法是什么list吗?

标签: pythonpandasmatplotlib

解决方案


推荐阅读