4

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().

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

"draw it yorself", then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.