![](/img/trans.png)
[英]Plotting multiple horizontal lines for each distribution in strip plot subplots Matplotlib
[英]Plot horizontal lines in subplots
我正在绘制水平线,但我得到的都是同一个 plot。我想要每个子图一条线。 我尝试使用ax
并确实得到了子图,但所有线条都绘制在最后一个子图中。 我能改变什么?
另外,我想为随机数组的每个 integer 分配一种颜色。 所以当我 plot 行时,我也看到了不同的 colors 而不仅仅是不同的长度。
我已经这样做了:
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)
谢谢!
您需要遍历轴实例并从每个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()
我不确定你到底在找什么,但如果你需要每个子图随机一行,那么你可以这样做:
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 循环更干净的解决方案,因此我决定编辑答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.