Djalil lounis
Djalil lounis

Reputation: 121

How to use Python and matplotlib to customize a bar chart

I am trying to plot a bar chart from a dictionary for Eg:

Dic = OrderedDict([('PROFESSIONAL_SERVICES', 621), ('WEB_SEARCH', 381), ('REMOTE_ACCESS', 160), ('Microsoft Category', 141), ('INTERNET_SERVICES', 62)])

I want to get a bar chart like the one in the following screenshot:

bar chart sample

Here is the code that I am using so far:

import matplotlib.pyplot as plt
from  Processesing import dataProcess

def chartmak (dic) :
    D={}
    D=dic
    plt.barh(range(len(D)), D.values(),align='center',color="#add8e6")
    plt.xticks(D.values, D.keys())
    plt.gca().invert_yaxis()
    plt.show()

NB: I am calling this function from another .py file

Any idea if it is possible to get a bar chart like the one in the screenshot?

Upvotes: 0

Views: 1441

Answers (2)

xnx
xnx

Reputation: 25478

Perhaps this will get you started. You can use annotate to add text labels at a specified point (in data coordinates) and explicitly set the y-tick labels. You can also turn off the border "spines" and remove the tick marks to get a closer look to the image you provide.

from collections import OrderedDict
import matplotlib.pyplot as plt

Dic = OrderedDict([('PROFESSIONAL_SERVICES', 621), ('WEB_SEARCH', 381), ('REMOTE_ACCESS', 160), ('Microsoft Category', 141), ('INTERNET_SERVICES', 62)])

fig, ax = plt.subplots()
n = len(Dic)
ax.barh(range(n), Dic.values(), align='center', fc='#80d0f1', ec='w')
ax.set_yticks(range(n))
ax.set_yticklabels(['{:3d} GB'.format(e) for e in Dic.values()], color='gray')
ax.tick_params(pad=10)
for i, (label, val) in enumerate(Dic.items()):
    ax.annotate(label.title(), xy=(10, i), fontsize=12, va='center')
for spine in ('top', 'right', 'bottom', 'left'):
    ax.spines[spine].set_visible(False)
ax.xaxis.set_ticks([])
ax.yaxis.set_tick_params(length=0)
plt.show()

enter image description here

Upvotes: 4

djangoliv
djangoliv

Reputation: 1788

Another solution...

import matplotlib.pyplot as plt
from collections import OrderedDict

def chartmak (dic) :
    plt.barh(range(len(dic)), dic.values(), 0.95, align='center', color="lightskyblue")
    plt.yticks(range(len(dic)), ["{} GB".format(v) for v in dic.values()])
    for index, label in enumerate(dic.keys()):
        plt.text(10, index, label, ha='left',va='center')
    plt.gca().invert_yaxis()
    plt.show()

Dic = OrderedDict([('PROFESSIONAL_SERVICES', 621), ('WEB_SEARCH', 381), ('REMOTE_ACCESS', 160), ('Microsoft Category', 141), ('INTERNET_SERVICES', 62)])
chartmak(Dic)

enter image description here

Upvotes: 1

Related Questions