Contour plot legend - Matplotlib

℡╲_俬逩灬. 提交于 2019-12-08 06:42:22

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/24830954/contour-plot-legend-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!