如何使用Python和matplotlib自定义条形图

时间:2016-01-05 11:58:06

标签: python matplotlib

我正在尝试从字典中为条形图绘制条形图:

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

我想获得一个类似下面屏幕截图中的条形图:

bar chart sample

以下是我目前使用的代码:

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

注意:我从另一个.py文件中调用此函数

是否有可能获得截图中的条形图?

2 个答案:

答案 0 :(得分:4)

也许这会让你开始。您可以使用annotate在指定点(数据坐标)添加文本标签,并明确设置y-tick标签。您还可以关闭边框“刺”并删除刻度线,以便仔细查看您提供的图像。

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

答案 1 :(得分:1)

另一种解决方案......

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