Matplotlib为一行多列创建表数据

时间:2017-05-02 17:59:51

标签: python matplotlib

我正在使用具有字符串(日期)和浮点时间(以毫秒为单位)的值字典。我想在条形图中以及下表中显示数据。我有条形图工作,但桌子搞砸了。我希望将日期作为列和时间作为单行。

字典就像:

time_and_dates_for_plot = {'04-26': 488.1063166666667, '04-27': 289.7289333333333, '04-28': 597.2343999999999, '04-29': 0, '04-30': 0, '05-01': 1061.958075}

plot.bar(range(len(time_and_dates_for_plot)), time_and_dates_for_plot.values(), align='center')
plot.xticks(range(len(time_and_dates_for_plot)), list(time_and_dates_for_plot.keys()))
plot.xlabel('Date (s)')
plot.ylabel('milliseconds')
plot.grid(True)
plot.gca().set_position((.1, .3, .8, .6))
col_labels = list(time_and_dates_for_plot.keys())
print(col_labels)
row_labels = ['ms']
cell_text = []
val = []

for key in time_and_dates_for_plot.keys():
    val.append((time_and_dates_for_plot.get(key)))
    cell_text.append(val)
    val = []
print(cell_text)
plot.table(cellText=cell_text, colLabels=col_labels)
plot.show()

Plot and table

从图中可以看出,我将所有条目都放在一列下,因为我想要一个单元格下的一个单元格数据(只是制表图数据)。

另外,如何在表格和图表之间添加一些填充?

我第一次使用matplotlib并且很确定我错过了什么。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:3)

table函数中,您需要一对额外的括号[]。 ...cellText=[cell_text]... Also, you can use subplots to have a better arrangement of the plots. Here, my solution uses subplots of 2 rows with height_ratios of 8 to 1, and a hspace` pf 0.3

import matplotlib as mpl
import matplotlib.pyplot as plt

time_and_dates_for_plot = {'04-26': 488.1063166666667,
                           '04-27': 289.7289333333333,
                           '04-28': 597.2343999999999,
                           '04-29': 0,
                           '04-30': 0,
                           '05-01': 1061.958075}

fig,axs = plt.subplots(figsize=(8,5),ncols=1,nrows=2,
                           gridspec_kw={'height_ratios':[8,1],'hspace':0.3})
ax = axs[0]
ax.bar(range(len(time_and_dates_for_plot)),
            time_and_dates_for_plot.values(), align='center')
ax.set_xticks(range(len(time_and_dates_for_plot)),
                list(time_and_dates_for_plot.keys()))
ax.set_xlabel('Date (s)')
ax.set_ylabel('milliseconds')
ax.grid(True)

col_labels = list(time_and_dates_for_plot.keys())
row_labels = ['ms']
cell_text = []

for key in time_and_dates_for_plot.keys():
    cell_text += [time_and_dates_for_plot[key]]

ax = axs[1]
ax.set_frame_on(False) # turn off frame for the table subplot
ax.set_xticks([]) # turn off x ticks for the table subplot
ax.set_yticks([]) # turn off y ticks for the table subplot
ax.table(cellText=[cell_text], colLabels=col_labels, loc='upper center')
plt.show()

输出如下:

enter image description here

** 更新 **

只使用一个子图,没有xticklabels,排序日期,带有%g的更好的数字,以及使用bbox的更大的表格单元格:

import matplotlib as mpl
import matplotlib.pyplot as plt

time_and_dates_for_plot = {'04-26': 488.1063166666667,
                           '04-27': 289.7289333333333,
                           '04-28': 597.2343999999999,
                           '04-29': 0,
                           '04-30': 0,
                           '05-01': 1061.958075}
N = len(time_and_dates_for_plot)
colLabels = sorted(time_and_dates_for_plot.keys())
fig,ax = plt.subplots()
aa = ax.bar(range(N),[time_and_dates_for_plot[x] for x in colLabels],
                    align='center')
ax.set_xlabel('Date')
ax.set_ylabel('milliseconds')
ax.set_xticklabels([]) # turn off x ticks
ax.grid(True)

fig.subplots_adjust(bottom=0.25) # making some room for the table

cell_text = []
for key in colLabels:
    cell_text += ["%g"%time_and_dates_for_plot[key]]

ax.table(cellText=[cell_text], colLabels=colLabels,
                    rowLabels=['ms'],cellLoc='center',
                    bbox=[0, -0.27, 1, 0.15])
ax.set_xlim(-0.5,N-0.5) # Helps having bars aligned with table columns
ax.set_title("milliseconds vs Date")
fig.savefig("Bar_graph.png")
plt.show()

输出:

enter image description here

** 更新:使用subplots_adjust **

为表格腾出空间