在图中移动图形位置(matplotlib) [英] Move graph position within plot (matplotlib)

查看:79
本文介绍了在图中移动图形位置(matplotlib)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用matplotlib中的表创建水平条形图.我快到了,但未能将表格与图表对齐.到目前为止,我得到了什么:

I am trying to create a horizontal bar graph with a table in matplotlib. I am almost there, but fail to align the table with the graph. What I got so far:

import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt


# Example data
appsol = ['llolLl', 'nnM', 'lllld bbbblnl', 'x2x', 'foobar', 'EXZ', 'Flups', 'Flaps', 'Foobar Barfooment', 'ABC', 'FABAS', 'common', 'AQT', 'Faberjak', 'simsalsa', 'LESS', 'Wermut']
y_pos = np.arange(len(appsol)) - .3
y_pos_2 = np.arange(len(appsol)) - .1
y_pos_3 = np.arange(len(appsol)) + .1
y_pos_4 = np.arange(len(appsol)) + .3
num_tickets = [4, 4,3,2,6,7,8,1,4,4,3,2,6,7,8,1,9]
num_tickets_2 = [7,6,5,4,3,4,2,1,2,4,1,0,3,0,2,1,0]
num_tickets_3 = [1,2,1,1,1,2,2,3,1,1,2,1,3,1,1,2,3]
num_tickets_4 = [8,7,6,2,13,6,8,9,7,6,5,4,3,6,8,9,12]

bar_width = .2

fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot(111)

# correct yticks
plt.yticks(y_pos_2, appsol)

plt.barh(y_pos, num_tickets, bar_width,  align='center', alpha=0.4, color='r')
plt.barh(y_pos_2, num_tickets_2, bar_width,  align='center', alpha=0.4, color='b')
plt.barh(y_pos_3, num_tickets_3, bar_width,  align='center', alpha=0.4, color='y')
plt.barh(y_pos_4, num_tickets_4, bar_width,  align='center', alpha=0.4, color='g')
plt.yticks(y_pos, appsol)
plt.xlabel('Numbers')
plt.title('Horizontal Bar Chart with table')

# Table

empty_labels = ['' for a in appsol ]
plt.yticks(y_pos_2, empty_labels)
plt.tick_params(\
    axis='y',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    left='off',      # ticks along the bottom edge are off
    right='off',         # ticks along the top edge are off
    labelbottom='off')

# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.4, bottom=0.2)

cell_text = []
i = len(num_tickets) - 1
for j in num_tickets:
    cell_text.append([num_tickets[i], num_tickets_2[i], num_tickets_3[i], num_tickets_4[i]])
    i -= 1

row_lables = appsol
column_labels = ['So Huge\nMice', 'Elephants', 'Reptiles', 'Germs']

the_table = ax.table(cellText=cell_text,
        rowLabels=row_lables,
        colLabels=column_labels,
        loc='left')
the_table.set_fontsize(15)
the_table.scale(.5,5.0)
plt.savefig('barh_graph.png')
plt.close('all')

这产生 几乎是我想要的,除了表格行没有与图形的条形.所以我需要一种方法来将图表向下移动半个表格行,或者将表格向上移动半个表格行.我该怎么办?

This produces almost what I want, except that the table rows are not aligned with the bars of the graph. So I need a way to either move the graph down half a table row, or the table up half a table row. How can I do this?

推荐答案

我认为,如果您创建两个子图并将表格添加到左子图,而不是从您现在拥有的单个子图导出新的子图,会更容易.如果将表格添加到现有子图中,则可以使用 bbox 在 y 方向上将其从 0 拉伸到 1(如此完整).由于该表具有标题,因此将右图的 ylim 设置为(0,n_items),将使两者均正确对齐,并添加一点偏移,因为小节的偏移也为0.4(外条的偏移量+半条宽度).如果元素数量发生变化,这应该会自动工作.

I think its easier if you create two subplots and add the table to the left subplot, instead of deriving a new subplot from the single subplot you have now. If you add the table to an existing subplot, you can use the bbox to stretch it from 0 to 1 (so fully) in the y-direction. Since the table has a header, setting the ylim of the right plot to (0, n_items), will make both align properly, and adding a slight offset because the bars are also given an offset of 0.4 (offset of the outer bar + half a barwidth). This should work automatically if the number of elements changes.

bar_width = .2

fig, axs = plt.subplots(1,2, figsize=(12,6))
fig.subplots_adjust(wspace=0, top=1, right=1, left=0, bottom=0)

axs[1].barh(y_pos[::-1], num_tickets[::-1], bar_width,  align='center', alpha=0.4, color='r')
axs[1].barh(y_pos_2[::-1], num_tickets_2[::-1], bar_width,  align='center', alpha=0.4, color='b')
axs[1].barh(y_pos_3[::-1], num_tickets_3[::-1], bar_width,  align='center', alpha=0.4, color='y')
axs[1].barh(y_pos_4[::-1], num_tickets_4[::-1], bar_width,  align='center', alpha=0.4, color='g')


axs[1].set_yticks([])
axs[1].set_xlabel('Numbers')
axs[1].set_title('Horizontal Bar Chart with table')
axs[1].set_ylim(0 - .4, (len(appsol)) + .4)

cell_text = list(zip(num_tickets, num_tickets_2, num_tickets_3, num_tickets_4))

row_lables = appsol
column_labels = ['So Huge\nMice', 'Elephants', 'Reptiles', 'Germs']

axs[0].axis('off')

the_table = axs[0].table(cellText=cell_text,
                     rowLabels=row_lables,
                     colLabels=column_labels,
                     bbox=[0.4, 0.0, 0.6, 1.0])

the_table.set_fontsize(15)

plt.savefig('barh_graph.png')
plt.close('all')

如果您仔细观察,您可能会注意到条形从表格的顶部到底部的范围,您可以稍微调整它们,使它们从表格的上下单元格的中心开始.

If you look closely you might notice that the bars are ranging from the top of the table to the bottom, you could tweak them a bit to make them start at the center of the upper and lower cell of the table.

这篇关于在图中移动图形位置(matplotlib)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆