【问题标题】:Modify matplolib legend in python在python中修改matplotlib图例
【发布时间】:2020-04-28 08:22:36
【问题描述】:

我目前使用以下代码来绘制我的数据。:

#
#Plotting
plt.plot(temp1, densityHEX,'bo',markersize='12',label='Hexadecane MD')
plt.plot(expTempHexa,expDensHexa,'bo',markersize='12',markerfacecolor='none',label='Hexadecane Exp')

plt.plot(temp2, densityLAU,'rs',markersize='12',label='Methyl Laurate MD')
plt.plot(expTempLau2,expDensLau2,'rs',markersize='12',markerfacecolor='none',label='Methyl Laurate Exp')

plt.plot(temp2, densityMIX,'^',color='indigo',markersize='12',label='Mixture 1:1 MD')
plt.plot(expTempMix,expDensMix,'^',color='indigo',markersize='12',markerfacecolor='none',label='Mixture 1:1 Exp')

leg = plt.legend(loc='best',ncol=2,frameon=False,prop={'size': 13})
leg.get_frame().set_edgecolor('k')
plt.ylabel(r'$\rho$ (g/cm$^3$)',fontsize = 22)
plt.xlabel('T (K)',fontsize = 22)
plt.ylim((0.650,1.0))
plt.tight_layout()
plt.savefig("rhoCombined3.pdf", format='pdf')

输出是这样的:

我想知道是否有办法修改图例以获得类似的东西:

【问题讨论】:

  • 您可以“滚动自己的”图例,但据我所知,matplotlib 开箱即用不支持这种类型的布局。

标签: python python-3.x matplotlib


【解决方案1】:

一个选项是这样的:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

x = np.arange(10)
y = x*0.2

#Plotting
l1, = plt.plot(x,y+0.0, 'bo', markersize='12', label='Hexadecane MD')
l2, = plt.plot(x,y+0.3, 'bo', markersize='12', markerfacecolor='none', label='Hexadecane Exp')

l3, = plt.plot(x,y+1.0, 'rs', markersize='12', label='Methyl Laurate MD')
l4, = plt.plot(x,y+1.3, 'rs', markersize='12', markerfacecolor='none', label='Methyl Laurate Exp')

l5, = plt.plot(x,y+2.0, '^', color='indigo', markersize='12', label='Mixture 1:1 MD')
l6, = plt.plot(x,y+2.3, '^', color='indigo', markersize='12', markerfacecolor='none',label='Mixture 1:1 Exp')

plt.legend(handles=[(l1, l2), (l3, l4), (l5, l6)], 
           labels=["Hexadecane", "Methyl Laurate", "Mixture 1:1"],
           handler_map={tuple: HandlerTuple(ndivide=2)}, 
           handlelength=3,
           title="MD  Exp                         ")
plt.show()

滥用“列标题”的标题是一种肮脏的技巧。但它很快给出了所需的输出。

【讨论】:

    猜你喜欢
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    相关资源
    最近更新 更多