2

I'd like to add a table to the right of two subplots using matplotlib. I tried the following code but it aligned the table with only one subplot...

import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(-1,1,100)

fig, axs = plt.subplots(2, 1, constrained_layout=True)
ax1, ax2 = axs

ax1.plot(t, t**2)
ax1.set_title('One plot')
ax1.set_xlabel('Time')
ax1.set_ylabel('Amplitude')
ax1.legend()

ax2.plot(t, t**3)
ax2.set_title('Another plot')
ax2.set_xlabel('Time')
ax2.set_ylabel('Amplitude')

clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
the_table = plt.table(cellText=clust_data,
                      colLabels=collabel,
                      loc='right')

I also tried to use Gridspec but without success. Thanks for your help!

1 Answers1

1

I came up with this workaround solution using plt.subplot. The idea of stretching it vertically is taken from here and to change the fontsize from here. You can choose the y-scaling value, which is 1.65 in the code below, as per your need.

ax1 = plt.subplot(221)
ax1.plot(t, t**2)
ax1.set_title('One plot')
ax1.set_xlabel('Time')
ax1.set_ylabel('Amplitude')

ax2 = plt.subplot(223)
ax2.plot(t, t**3)
ax2.set_title('Another plot')
ax2.set_xlabel('Time')
ax2.set_ylabel('Amplitude')

ax3 = plt.subplot(122)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
the_table = ax3.table(cellText=clust_data,
                      colLabels=collabel,
                      loc='center')
the_table.scale(1,1.65)
the_table.auto_set_font_size(False)
the_table.set_fontsize(4)
ax3.axis('off')
plt.tight_layout()

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71