python 条形图图注怎么集中_python – 如何在matplotlib中为条形图添加组标签?

由于我在matplotlib中找不到一个内置的解决方案,我编码自己的:

#!/usr/bin/env python

from matplotlib import pyplot as plt

def mk_groups(data):

try:

newdata = data.items()

except:

return

thisgroup = []

groups = []

for key, value in newdata:

newgroups = mk_groups(value)

if newgroups is None:

thisgroup.append((key, value))

else:

thisgroup.append((key, len(newgroups[-1])))

if groups:

groups = [g + n for n, g in zip(newgroups, groups)]

else:

groups = newgroups

return [thisgroup] + groups

def add_line(ax, xpos, ypos):

line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],

transform=ax.transAxes, color='black')

line.set_clip_on(False)

ax.add_line(line)

def label_group_bar(ax, data):

groups = mk_groups(data)

xy = groups.pop()

x, y = zip(*xy)

ly = len(y)

xticks = range(1, ly + 1)

ax.bar(xticks, y, align='center')

ax.set_xticks(xticks)

ax.set_xticklabels(x)

ax.set_xlim(.5, ly + .5)

ax.yaxis.grid(True)

scale = 1. / ly

for pos in xrange(ly + 1):

add_line(ax, pos * scale, -.1)

ypos = -.2

while groups:

group = groups.pop()

pos = 0

for label, rpos in group:

lxpos = (pos + .5 * rpos) * scale

ax.text(lxpos, ypos, label, ha='center', transform=ax.transAxes)

add_line(ax, pos * scale, ypos)

pos += rpos

add_line(ax, pos * scale, ypos)

ypos -= .1

if __name__ == '__main__':

data = {'Room A':

{'Shelf 1':

{'Milk': 10,

'Water': 20},

'Shelf 2':

{'Sugar': 5,

'Honey': 6}

},

'Room B':

{'Shelf 1':

{'Wheat': 4,

'Corn': 7},

'Shelf 2':

{'Chicken': 2,

'Cow': 1}

}

}

fig = plt.figure()

ax = fig.add_subplot(1,1,1)

label_group_bar(ax, data)

fig.subplots_adjust(bottom=0.3)

fig.savefig('label_group_bar_example.png')

“mk_groups”函数使用一个字典(或任何带有items()方法的东西,如collections.OrderedDict),并将其转换为数据格式,然后用于创建图表.它基本上是一个表单列表:

[ [(label, bars_to_span), ...], ..., [(tick_label, bar_value), ...] ]

“add_line”函数在指定位置(轴坐标)中的子图中创建垂直线.

“label_group_bar”函数使用字典,并在子图中创建带有下面标签的条形图.从示例的结果看起来like this.

更容易或更好的解决方案和建议仍然非常感激.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值