reckoner
reckoner

Reputation: 2981

Using Matplotlib to create a partial multiplication table checkerboard?

My kid is trying to learn his multiplication tables and I was thinking of using matplotlib to create a partially filled out multiplication table for him to practice on. The tricky part is to have the text of the horizontal and vertical axes line up between the tic marks instead of being centered on the tic marks.

Any ideas about how to get started with this?

thanks in advance.

Upvotes: 2

Views: 959

Answers (1)

Joe Kington
Joe Kington

Reputation: 284850

As everyone has already said, matplotlib is really not the best tool for this... If you really want to do it programatically, generating HTML would honestly be easier.

That having been said, it makes a nice example.

The easiest way to tweak the axis label positions is to either replace them with text objects or just leave them as they are and turn on the minor grid. (The label objects have a set_position method, but it doesn't actually change their position. I'm not sure if this is deliberate or a bug...) I'm going to use the latter technique here...

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np

maxnum = 13
numfilled = 40
x = np.random.randint(0, maxnum, size=numfilled)
y = np.random.randint(0, maxnum, size=numfilled)
z = x * y

fig, ax = plt.subplots()

for X,Y,Z in zip(x,y,z):
    ax.text(X+0.5,Y+0.5,str(Z), ha='center', va='center')

ax.axis([0, maxnum, 0, maxnum])

for axis in [ax.xaxis, ax.yaxis]:
    axis.set_minor_locator(MultipleLocator(1))
    axis.set_ticks(np.arange(maxnum) + 0.5)
    axis.set_ticklabels(range(maxnum))

ax.grid(which='minor')
ax.xaxis.set_ticks_position('top')

plt.show()

enter image description here

Upvotes: 6

Related Questions