Contour plot legend - Matplotlib

2019-05-31 08:49发布

As the question says, I have a contour plot and I would like show a legend for if.

I'm using the contour plot style that uses:

dashed lines for negative levels

solid lines for positive values

I would like to have a legend for them (dashed == negative and solid == positive).

I tried the approaches found here and here. However, as can be seen below, this doesn't show the correct result.

# 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])

enter image description here

As I for the div scalar field I just have positive levels, I got two labels with the same line style.

I'm wondering how could I achieve what I want properly.

Thank you in advance.

2条回答
叼着烟拽天下
2楼-- · 2019-05-31 09:13

Something like the following works for me - this complete hack is to use a labelled dummy point, fetch its colour, apply that to the contours and then just plot the legend in the usual way:

    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')

Hope that makes sense.

查看更多
相关推荐>>
3楼-- · 2019-05-31 09:21

I could solve this manually setting the legend (which I don't know if it's the best approach):

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'])

enter image description here

查看更多
登录 后发表回答