如何用matplotlib关联子批次中的两点

2024-06-16 09:38:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从一个名为('BW1\u StartValues')的excel文件中导入3列值(C,h,L*),它们表示用数字定义颜色的坐标。L、C、h的每一行定义一种特定的颜色

我想创建一个交互式散点子图,有两个图形,一个是我绘制C和h,另一个是我沿着垂直线绘制L。我希望能够关联两个图中的每个点,例如,当我单击第一个图中的一个点时,我会在第二个图中看到它的相关值

我在stackoverflow上发现了一段类似于我想要的代码,但是当我从文件导入数据然后尝试使用代码时遇到了问题。我对Python比较陌生,找不到我的代码哪里出错了

谢谢你的帮助! 高蒂埃

def main():

    fig, (ax1,ax2) = plt.subplots(nrows=1, ncols=2, figsize=(15,8))
    gs = gridspec.GridSpec(1, 2, width_ratios=[8, 1]) 

    df1 = read_excel('BW1_StartValues.xlsx')
    C = df1['C']
    h = df1['h']
    L = df1['L*']  

    x1 = np.ones((14,1))

    for (ax1,ax2), marker in zip((ax1,ax2), ['o', 'o']):
        x = C
        y = h
        x,y = x,y

    ax1 = fig.add_subplot(gs[0])

    ax1.plot(h,C, ls='',marker = marker, label = 'BW1 samples' )
    ax1.plot(h_mean, C_mean, ls='',marker = marker, color='red', label = 'mean value')

    ax1.set_xlabel('h', fontsize = 14)
    ax1.set_ylabel('C*', fontsize = 14)
    ax1.legend(loc='lower right', fontsize = 15)
    ax1.set_xlim(255,280)
    ax1.set_ylim(25,50)

    ax2 = fig.add_subplot(gs[1])

    axe2.set_ylabel('L*', fontsize = 14)

    ax2.yaxis.set_ticks_position('both')
    ax2.set_xlim(0.8,1.2,1)
    ax2.tick_params(labelleft='off',labelright='on')
    ax2.yaxis.set_label_position('right')

    plt.suptitle('BW1 samples', y = 0.95)



    ax2.plot(x1, L, ls='', marker=marker)
    ax2.plot(1, L_mean, ls='', marker=marker, color='red')

    plt.subplots_adjust(wspace=0.05, top =0.95)


    IndexedHighlight((ax1,ax2))
    plt.show()

class IndexedHighlight(HighlightingDataCursor):
    def __init__(self, axes, **kwargs):
        # Use the first plotted Line2D in each axes
        artists = [ax.lines[0] for ax in axes]

        kwargs['display'] = 'single'
        HighlightingDataCursor.__init__(self, artists, **kwargs)
        self.highlights = [self.create_highlight(artist) for artist in artists]
        plt.setp(self.highlights, visible=False)

    def update(self, event, annotation):
        # Hide all other annotations
        plt.setp(self.highlights, visible=False)

        # Highlight everything with the same index.
        artist, ind = event.artist, event.ind
        for original, highlight in zip(self.artists, self.highlights):
            h, C = original.get_data()
            highlight.set(visible=True, xdata=h[ind], ydata=C[ind])
        DataCursor.update(self, event, annotation)

main()

Tags: inselfforplotpltmeanlsmarker