简体   繁体   中英

Contour plot legend - Matplotlib

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

在此处输入图片说明

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.

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

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM