使用Matplotlib创建部分乘法表棋盘?

2 投票
1 回答
935 浏览
提问于 2025-04-16 19:03

我孩子正在学习乘法表,我想用matplotlib这个工具为他制作一个部分填好的乘法表,让他可以练习。比较棘手的地方是,想让横轴和纵轴的文字对齐在刻度线之间,而不是正好在刻度线的中间。

有没有什么建议可以让我开始做这个呢?

提前谢谢你!

1 个回答

6

大家都说过,matplotlib其实并不是做这个的最佳工具……如果你真的想通过编程来实现,生成HTML会简单得多。

不过,虽然这样说,它还是一个不错的例子。

调整坐标轴标签位置最简单的方法是用文本对象替换它们,或者就保持原样,开启次要网格线。(标签对象有一个 set_position 方法,但实际上并不会改变它们的位置。我不确定这是故意的还是个bug……)在这里我会用后者的方法……

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

撰写回答