Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding dotted lines to Bar chart in Python

I need a bit of help with Python modules and code.

I want to create bar graph for the following data:

Data

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and the bar chart should look somewhat like this:
Bar chart

While it has been easy to plot bar chart and label it using plotly, I am unable to add the lines with text box and a box around second bar.

Can you please help me with it?

>Solution :

You can use a simple loop with plot and text:

df = pd.DataFrame({'data': [100, 60]}, index=['potential', 'expected'])

ax = df.plot.bar()

texts = ['this is line A', 'this is line B']

for i, v in enumerate(df['data']):
    print(i,v)
    ax.plot([i+0.25, ax.get_xlim()[-1]], [v, v],
            ls='--', c='k')
    ax.text(ax.get_xlim()[-1]+0.1, v, texts[i])

output:

enter image description here

For the rectangle, you need to compute some width around your bars:

import matplotlib.patches as patches
r = patches.Rectangle((1-0.3, 0), 0.6, 60*1.05,
                      lw=3, ls='--',
                      edgecolor='#ED7D31', facecolor='none'
                     )
ax.add_patch(r)

output:

enter image description here

Alternative for rectangle outside the axes:

import matplotlib.patches as patches
r = patches.Rectangle((1-0.3, -60*0.05), 0.6, 60*1.1,
                      lw=3, ls='--',
                      edgecolor='#ED7D31', facecolor='none',
                      clip_on=False
                     )
ax.add_patch(r)

output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading