How to align x-position of samples with table columns in matplotlib.pyplot?

Viewed 423

I have a figure containing a graph and two tables.

I want to align the x-position of each sample with the center of the respective column.

The amount of columns is the same as the amount of samples to plot.

I have found this related question, which covers the same question but for a bar chart.

I couldn't transfer the result to my case.

Here is a minimal, working code example:

import matplotlib.pyplot
import numpy as np

a = np.arange(20)
b = np.random.randint(1, 5, 20)
fig, ax = plt.subplots()

ax.plot(a, b, marker='o')
ax.table(np.random.randint(1, 5, (4, 20)), loc="top")
ax.table(np.random.randint(1, 5, (4, 20)))
ax.set_xticklabels([])


plt.subplots_adjust(top=0.85, bottom=0.15)
fig.savefig('test.png')

It creates this output:

enter image description here

As you can see, the circles representing the samples are not centered towards the respective columns.

Any help appreciated!

1 Answers

For me it always worked to change the xlim and thereby hardcoding the alignment.

plt.xlim(left=first-0.5, right=last+0.5)

integrating this into your example would lead to:

import matplotlib.pyplot
import numpy as np

a = np.arange(20)
b = np.random.randint(1, 5, 20)
fig, ax = plt.subplots()

ax.plot(a, b, marker='o')
ax.table(np.random.randint(1, 5, (4, 20)), loc="top")
ax.table(np.random.randint(1, 5, (4, 20)))
ax.set_xticklabels([])
plt.xlim(left=a[0]-0.5, right=a[-1]+0.5)

plt.subplots_adjust(top=0.85, bottom=0.15)
fig.savefig('test.png')

Hope that helps!

Related