【问题标题】:Matplotlib Reduce the Thickness of Plot Legend Line for a Pot with Two y-axes?Matplotlib 减少带有两个 y 轴的锅的图例线的厚度?
【发布时间】:2017-06-14 17:40:43
【问题描述】:

我有一个 Python3.6 代码,它生成两个绘图,一个具有三个轴,一个具有两个轴。三轴绘图有一个细线图例。

不幸的是,第二个情节图例的线条粗细等于标签的高度:

这是第二个图的代码:

一个图上有两个图

如何减少图例中线条的粗细?

该代码似乎没有发布到帖子中。

这里是:

#two plots on one figure

def two_scales(ax1, time, data1, data2, c1, c2):
   
    ax2 = ax1.twinx()

    ax1.plot(time, data1, 'r')
    ax1.set_xlabel("Distance ($\AA$)")
    ax1.set_ylabel('Atom Charge',color='r')

    ax2.plot(time, data2, 'b')
    ax2.set_ylabel('Orbital Energy',color='b')
    return ax1, ax2



t = data[:,0]
s1 = data[:,3]
s2 = data[:,5]

fig, ax = plt.subplots()
ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')


def color_y_axis(ax, color):
    for t in ax.get_yticklabels():
        t.set_color(color)
    return None
color_y_axis(ax1, 'r')
color_y_axis(ax2, 'b')

plt.title('Molecular Transforms')

patch_red = mpatches.Patch(color='red',label='Atom Charge')
patch_blue = mpatches.Patch(color='blue',label='Orbital Energy')
plt.legend(handles = [patch_red,patch_blue])

plt.draw()
plt.show()

name_plt = name+'-fig2.png'
fig.savefig(name_plt,bbox_inches='tight')

【问题讨论】:

  • 非常感谢您的解决方案。现在问题已经解决了。

标签: python matplotlib plot


【解决方案1】:

听起来您想要为您的图例添加一行,但实际上使用了补丁。示例和详细信息可以在here 找到。你可以像这个小例子那样使用线:

import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_red = mlines.Line2D([], [], color='red',label='Atom Charge')
line_blue = mlines.Line2D([], [], color='blue',label='Orbital Energy')
plt.legend(handles = [line_red,line_blue])
plt.show()

【讨论】:

    【解决方案2】:

    为图例创建标签的常用方法是使用艺术家的label 参数在图例中显示ax.plot(...., label="some label")。使用具有此标签集的实际艺术家,确保图例显示与艺术家相对应的符号;如果是线图,这自然是一条线。

    import matplotlib.pyplot as plt
    
    time=[1,2,3,4]; data1=[0,5,4,3.3];data2=[100,150,89,70]
    
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    
    l1, = ax1.plot(time, data1, 'r', label='Atom Charge')
    ax1.set_xlabel("Distance ($\AA$)")
    ax1.set_ylabel('Atom Charge',color='r')
    
    l2, = ax2.plot(time, data2, 'b', label='Orbital Energy')
    ax2.set_ylabel('Orbital Energy',color='b')
    
    
    ax1.legend(handles=[l1,l2])
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2013-01-07
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      相关资源
      最近更新 更多