【问题标题】:Contour plot legend - Matplotlib等高线图图例 - Matplotlib
【发布时间】:2014-09-09 22:37:53
【问题描述】:

正如问题所说,我有一个等高线图,我想为 if 显示一个图例。

我正在使用等高线绘图样式:

虚线表示水平

实线表示

我想给他们一个图例(虚线 == 负数,实线 == 正数)。

我尝试了找到herehere 的方法。但是,如下所示,这并没有显示正确的结果。

# Draw the scalar field level curves
div_field = plt.contour(x, y, div_scalar_field, colors='white')
rot_field = plt.contour(x, y, rot_scalar_field, colors='lightgoldenrodyellow')
labels = ['Div Neg', 'Div Pos', 'Rot Neg', 'Rot Pos']
div_field.collections[0].set_label(labels[0])
div_field.collections[-1].set_label(labels[1])
rot_field.collections[0].set_label(labels[2])
rot_field.collections[-1].set_label(labels[3])

对于 div 标量 字段,我只有正水平,所以我得到了两个具有相同线条样式的标签。

我想知道我怎样才能正确地实现我想要的。

提前谢谢你。

【问题讨论】:

    标签: python matplotlib plot legend contour


    【解决方案1】:

    我可以手动设置图例来解决这个问题(我不知道这是否是最好的方法):

    div_neg = plt.Line2D((0, 1), (0, 0), color='white', linestyle='--', linewidth=2)
    div_pos = plt.Line2D((0, 1), (0, 0), color='white', linestyle='-', linewidth=2)
    rot_neg = plt.Line2D((0, 1), (0, 0), color='lightgoldenrodyellow', linestyle='--', linewidth=2)
    rot_pos = plt.Line2D((0, 1), (0, 0), color='lightgoldenrodyellow', linestyle='-', linewidth=2)
    
    plt.legend([rot_max, div_neg, div_pos, rot_neg, rot_pos],
               ['Rot Max Points', 'Div Neg', 'Div Pos', 'Rot Neg', 'Rot Pos'])
    

    【讨论】:

      【解决方案2】:

      以下内容对我有用 - 这个完整的技巧是使用标记的虚拟点,获取其颜色,将其应用于轮廓,然后以通常的方式绘制图例:

          import matplotlib as plt
      
          labels = ['div_field'] # etc.
      
          dummy_position = [-1.0e3,-1.0e3] # Could automate
      
          colors = []
          for k in labels:
      
              # Fetch colours via a dummy point
              dummy_point = plt.plot(dummy_position[0],dummy_position[1], label = k)
              c = dummy_point[-1].get_color()
              colors.append(c)
      
              # This is specific to your problem, but roughly:
              div_field = plt.contour(x, y, div_scalar_field, colors=c)
              # etc.
      
          _=plt.legend()
      
          plt.savefig('contours.pdf')
      

      希望这是有道理的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-04
        相关资源
        最近更新 更多