在一张图中创建图例并绘制多个数据集

2 投票
1 回答
6066 浏览
提问于 2025-04-18 18:13

我是一名生物学家,正在学习Python编程。我有一段代码用来处理我的数据。不过,我遇到了一个问题,就是我想画一个包含所有数据集的图表,并且图例不在图表的上面。我有很多数据,而目前的代码一次只能画一个图,这样不太方便,因为我需要对比这些数据。有没有人能帮我,给我一些建议,如何才能把所有数据画在一个图上,并且图例放在图外?以下是代码的一部分:

def plotcorrected(self, conditions= 'all', strains= 'all'):
        '''
        Plots the corrected fluorescence per cell for all strains in all conditions.
        '''
        S, t= self.d, self.t
        if conditions == 'all':
            cons= S.keys()
            if 'media' in cons:
                cons.pop(cons.index('media'))
        else:
            cons= gu.makelist(conditions)
            #draw all plots
        if onefig:
            plt.figure()
        for c in cons:
            if strains == 'all':
                strains=  S[c].keys()
            else:
                strains= gu.makelist(strains)
            for s in strains:
                if not onefig:
                    plt.figure()
                if s != 'null' and s != 'WT':
                    #plt.figure()
                    plt.plot(t, S[c][s]['mg'], '.-')
                    plt.plot(t, S[c][s]['mg']+S[c][s]['sg'], 'k:', alpha=0.4)
                    plt.plot(t, S[c][s]['mg']-S[c][s]['sg'], 'k:', alpha=0.4)
                if not onefig:
                    plt.xlabel('time (hours)')
                    plt.ylabel('corrected fluorescence')
                    plt.title('corrected ' + s + ' in ' + c)
                    plt.show()
        if onefig:
                    plt.xlabel('time (hours)')
                    plt.ylabel('corrected fluorescence')
                    plt.title('corrected ' + s + ' in ' + c)
                    plt.show()

1 个回答

4

要在一个图中画出所有的线,只需要调用一次 plt.figure()(或者 plt.subplots()),因为每次调用都会创建一个新的图。目前(当 onefigTrue 时),你在一个 for-loop 里调用了 plt.figure(),这就是为什么你得到多个图,而不是把所有线都画在一个图里的原因。

如果你想把图例移到图的绘制区域外面,可以使用

leg = ax.legend(loc=2, bbox_to_anchor=(1.05, 1.0))

这样可以把图例放在右上角附近。

例如,

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2*np.pi*x)
y2 = np.exp(-x)
ax.plot(x, y1, 'rs-', label='Line 1')
ax.plot(x, y2, 'go', label='Line 2')

y3 = np.sin(4*np.pi*x)
y4 = np.exp(-2*x)
ax.plot(x, y3, 'yd-', label='Line 3')
ax.plot(x, y4, 'k^', label='Line 4')

leg = ax.legend(loc=2, bbox_to_anchor=(1.05, 1.0))
plt.savefig('/tmp/test.png', bbox_inches='tight')

在这里输入图片描述

bbox_to_anchor=(1.05, 1.0) 是把图例固定在图的右上角外面一个点。

loc=2 把图例的左上角固定在位置 (1.05, 1.0)

感谢 DSM 展示了如何移动图例,在这里可以找到更多信息。关于如何放置和配置图例的更多信息,可以查看 图例指南

撰写回答