Skip to content
Advertisement

Add diagonal line to hist2d with matplotlib

I am analyzing the heights/widths of some ML label boxes by creating a 2D histogram with matplotlib:

plt.hist2d(widths, heights, 100, [(0, 0.1), (0, 0.1)])
plt.gca().set_aspect(aspect=1)

plt.savefig(outimage)

enter image description here

But I want to add a semi-transparent diagonal line from (0,0) to (0.1,0.1)–the line indicating a square label box–to emphasize how the majority of the aspect ratios tend towards the tall and narrow.

I’ve tried adding this line both before the hist2d() call and after:

plt.plot(0, 0, 0.1, 0.1, marker = "o")

But as you can see in the picture, it just creates the endpoint dots, not the line. How do I add a line on top of the existing plot, ideally a semi-transparent line?

Advertisement

Answer

You should pass the coordinates of the line plot as a list of x values and a list of y values. For the transparency you can use the alpha parameter. So your code for the line should be

plt.plot([0, 0.1], [0, 0.1], marker="o", alpha=0.5)
Advertisement