在子图中绘制水平线

Plot horizontal lines in subplots

我正在绘制水平线,但我把所有的都放在同一个图中。我想要每个子图一行。我尝试使用 ax 并且确实得到了子图,但所有线条都绘制在最后一个子图中。 我可以改变什么?

此外,我想为随机数组的每个整数分配一种颜色。因此,当我绘制线条时,我还会看到不同的颜色,而不仅仅是不同的长度。

我已经这样做了:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(3, 3)
randnums= np.random.randint(0,10,9)
y= np.random.randint(1,10,9)
print(randnums)

plt.hlines(y=y, xmin=1, xmax=randnums)

谢谢!

我不确定你到底在找什么,但如果你需要每个子图随机一行,那么你可以这样做:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(3, 3, figsize=(10, 10), sharex=True, sharey=True)
line_lengths = np.random.randint(0, 10 ,9)
ys = np.random.randint(1, 10 ,9)

colors = plt.cm.rainbow(np.linspace(0, 1, len(ys)))

for y, line_length, color, ax in zip(ys, line_lengths, colors, axes.flat):
    ax.hlines(y=y, xmin=1, xmax=line_length, colors=color)

编辑:将 的解决方案与 zip 一起使用绝对是比嵌套 for 循环更干净的解决方案,因此我决定编辑答案。

您需要遍历轴实例并从每个 Axes 调用 hlines。要分配颜色,您可以从颜色图中创建颜色列表并同时对其进行迭代。例如:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

fig, axes = plt.subplots(3, 3, sharex=True, sharey=True)

colours = [cm.viridis(i) for i in np.linspace(0, 1, 9)]

randnums = np.random.randint(0, 10, 9)

y = np.random.randint(1, 10, 9)
print(randnums)

for yy, num, col, ax in zip(y, randnums, colours, axes.flat):

    ax.hlines(y=yy, xmin=1, xmax=num, color=col)

axes[0, 0].set_xlim(0, 10)
axes[0, 0].set_ylim(0, 10)

plt.show()