Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib create table data for one row multiple columns

I'm working with a dictionary of values which have a string (date) and float for time in milliseconds. I want to present the data in a bar graph and also with a table below. I have the bar graph working but the table gets messed up. I want the dates as columns and time as a single row.

The dictionary is something like:

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

As you can see from the picture, I get all entries under one column where as I want something like one cell data under one coloumn (just tabulate plot data).

Also, how do I add some padding between the table and graph?

First time I'm using matplotlib and pretty sure I'm missing something. Any help is really appreciated.

like image 322
Srikkanth Govindaraajan Avatar asked Jul 25 '26 20:07

Srikkanth Govindaraajan


1 Answers

In the table function you need an extra pair of brackets []. ...cellText=[cell_text]... Also, you can use subplots to have a better arrangement of the plots. Here, my solution uses subplots of 2 rows withheight_ratiosof 8 to 1, and ahspace` 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()

The output looks like:

enter image description here

** UPDATE **

Using only one subplot, no xticklabels, sorted dates, nicer numbers with %g, and larger table cells using 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()

Output:

enter image description here

** Update: Making room for the table using subplots_adjust **

like image 133
Pablo Reyes Avatar answered Jul 27 '26 10:07

Pablo Reyes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!