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

标签 python graph matplotlib legend

我是一名正在学习 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()

最佳答案

要绘制一个图形中的所有线条,请仅调用 plt.figure() (或 plt.subplots())一次,因为每次调用都会创建一个新图形。目前(当 onefigTrue 时)您可以在 for 循环 内调用 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')

enter image description here

bbox_to_anchor=(1.05, 1.0) 将图例锚定到图形外部的点 在右上角。

loc=2 anchors the upper left corner图例到位置 (1.05, 1.0)

感谢 DSM 展示如何移动图例,here 。 有关如何放置和配置图例的更多信息,请参阅 the Legend Guide .

关于python - 创建图例并在一张图中绘制多个数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453141/

相关文章:

python - 我无法在 anaconda 环境中安装 Jupyter 和 Matplotlib

python - 在 pathlib.Path 上模拟 open() 以使用 unittest.mock 返回模拟文件句柄

将文件上传到 REST URL 的 Python 3 脚本(多部分请求)

python - df.loc 过滤不适用于 None 值

c++ - 多条路径的最短和

python - 考虑权重的networkx is_isomorphic

python - matplotlib 调整图像大小

python - URL 以/开头时 XML2PDF 抛出异常

python-3.x - python - 如何在循环中创建字典字典

python - 如何使用 matplotlib 设置基线并让条形图向下增长