简体   繁体   中英

Plot horizontal lines in subplots

I am plotting horizontal lines but I am getting all in the same plot. I want a line per subplot. I tried using ax and I do get the subplots but all the lines are plotted in the last subplot. What can I change?

Also, I want to assign a color to each integer of the random array. So when I plot the lines, I also see the different colors and not just the different lengths.

I already did this:

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)

Thank you!

You need to loop over the axes instances and call hlines from each Axes . To assign colours, you could create a list of colours from the colormap and iterate over that too at the same time. For example:

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()

在此处输入图像描述

I'm not sure exactly what are you looking for, but if you need one random line per subplot, then you can do this:

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)

Edit: using tmdavison 's solution with zip is definitely a cleaner solution than nested for loops, so I decided to edit the answer.1个

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM