【问题标题】:Plot horizontal lines in subplots在子图中绘制水平线
【发布时间】:2020-08-19 08:07:55
【问题描述】:

我正在绘制水平线,但我都在同一个图中。我想要每个子图有一条线。我尝试使用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)

谢谢!

【问题讨论】:

  • 你想要每个子图 1 行吗?
  • @user195366 通常,请避开状态机方法 (plt.method),因为如果您有多个人物或斧头,它永远不会按照您的意愿行事。通常,函数调用会影响您修改的最后一个图形或斧头。 ax.method 更清晰,如各种答案所示。

标签: python matplotlib subplot


【解决方案1】:

您需要遍历坐标区实例并从每个 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()

【讨论】:

    【解决方案2】:

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

    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)
    

    编辑:使用tmdavison 的解决方案和zip 绝对是比嵌套for 循环更清洁的解决方案,所以我决定编辑答案。

    【讨论】:

    • 是的,这就是我要找的!你知道我如何根据随机数组分配颜色吗?谢谢!
    • j 实际上是一个神秘的变量名。 fig, axes = ... 然后for i, ax in enumerate(axes): 怎么样?
    • @Guimute 是的,当然,我会重写变量名。
    • @tmdavison 我刚刚意识到它更好:) 我应该删除它吗?
    • 我的意思是,我真的不喜欢这样的小事,但是当你复制别人的代码至少给他们荣誉时,这是一种很好的做法