【问题标题】:Printing multiple list name on the legend在图例上打印多个列表名称
【发布时间】:2021-09-07 19:23:59
【问题描述】:

我想在图例上打印列表名称而不是打印列表。任何的想法? 代码如下:

import numpy as np

m = [x,y]
fig = plt.figure()
ax = plt.subplot(111)
#j = ["1","1","1","1","1"]

for i in m:
    ax.plot(i, label='$variable = %s$'%i)

# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

# Put a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

在图例中我想要变量 = x 和变量 = y

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    ['x','y'] 作为第一个参数传递给 ax.legend 方法。

    ax.legend(['x','y'], loc='center left', bbox_to_anchor=(1, 0.5))
    

    【讨论】:

      【解决方案2】:

      打印列表的原因是因为行:

      m = [x,y]
      

      由于 x 和 y 是包含数组的变量,python 正在打印数组。假设您想要数组名称,即“x”和“y”具有相同的容量,您必须执行以下操作:

      m = [x,y]
      n=['x','y']
      fig = plt.figure()
      ax = plt.subplot(111)
      #j = ["1","1","1","1","1"]
      
      for i in n:
          ax.plot(i, label='$variable = %s$'%i)
      

      你也可以创建一个字典:

      m = {'x':x,'y':y}
      fig = plt.figure()
      ax = plt.subplot(111)
      #j = ["1","1","1","1","1"]
      
      for i in m:
          ax.plot(i, label='$variable = %s$'%i)
      

      【讨论】:

        【解决方案3】:

        这可能是一种可能性:

        import numpy as np
        
        m = [x,y]
        n = ["x","y"]
        fig = plt.figure()
        ax = plt.subplot(111)
        #j = ["1","1","1","1","1"]
        
        for i,j in zip(m,n):
            ax.plot(i, label='$variable = %s$'%j)
        
        # Shrink current axis by 20%
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
        
        # Put a legend to the right of the current axis
        ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        
        plt.show()
        

        #工作代码。

        【讨论】:

        • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
        猜你喜欢
        • 1970-01-01
        • 2019-09-17
        • 2021-08-10
        • 2016-09-03
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 2017-12-20
        • 1970-01-01
        相关资源
        最近更新 更多