Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I label a span of values on matplotlib axis?

In my histogram, I need to annotate the X-axis like that: enter image description here

The "0" label is spanning between two ticks since there is a separate bin for 0s only in the histogram, while rest of the axis is linear to indicate boundaries of other bins. The underbrace is not crucial, but there shall be some indicator that "0" spans for entire bin.

The closest solution I found so far is "draw it yourself" (How to add group labels for bar charts in matplotlib?). I am looking rather for .axvspan() equivalent for axis (as .axvline() is for ticks), like something intended for labelling .axvspan().

like image 721
abukaj Avatar asked Mar 08 '23 07:03

abukaj


1 Answers

There is no ".axvspan() equivalent for axis". Also ".axvline()" is not "for ticks". And there is also nothing intended for labeling .axvspan().

So let's answer the question how to produce some red bracket (paranthesis) below the plot. You can basically just plot a line in form of the bracket and position it according to the xaxis transform. Below is a function to do that.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.bar(range(-1,5),range(3,9), width=1, align="edge", ec="k", alpha=1)
ax.set_xticks(range(1,6))


def bracket(ax, pos=[0,0], scalex=1, scaley=1, text="",textkw = {}, linekw = {}):
    x = np.array([0, 0.05, 0.45,0.5])
    y = np.array([0,-0.01,-0.01,-0.02])
    x = np.concatenate((x,x+0.5)) 
    y = np.concatenate((y,y[::-1]))
    ax.plot(x*scalex+pos[0], y*scaley+pos[1], clip_on=False, 
            transform=ax.get_xaxis_transform(), **linekw)
    ax.text(pos[0]+0.5*scalex, (y.min()-0.01)*scaley+pos[1], text, 
                transform=ax.get_xaxis_transform(),
                ha="center", va="top", **textkw)

bracket(ax, text="0", pos=[-1,-0.01], linekw=dict(color="crimson", lw=2) )
plt.show()

enter image description here

like image 105
ImportanceOfBeingErnest Avatar answered Mar 10 '23 06:03

ImportanceOfBeingErnest