Set a colormap under a graph

不羁岁月 提交于 2021-02-08 04:22:11

问题


I know this is well documented, but I'm struggling to implement this in my code.

I would like to shade the area under my graph with a colormap. Is it possible to have a colour, i.e. red from any points over 30, and a gradient up until that point?

I am using the method fill_between, but I'm happy to change this if there is a better way to do it.

def plot(sd_values):

    plt.figure()
    sd_values=np.array(sd_values)
    x=np.arange(len(sd_values))
    plt.plot(x,sd_values, linewidth=1)
    plt.fill_between(x,sd_values, cmap=plt.cm.jet)
    plt.show()

This is the result at the moment. I have tried axvspan, but this doesnt have cmap as an option. Why does the below graph not show a colormap?

enter image description here


回答1:


I'm not sure if the cmap argument should be part of the fill_between plotting command. In your case probably want to use the fill() command btw.

These fill commands create polygons or polygon collections. A polygon collection can take a cmap but with fill there is no way of providing the data on which it should be colored.

What's (for as far as i know) certainly not possible is to fill a single polygon with a gradient as you wish.

The next best thing is to fake it. You can plot a shaded image and clip it based on the created polygon.

# create some sample data
x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x) * 120

fig, ax = plt.subplots()

# plot only the outline of the polygon, and capture the result
poly, = ax.fill(x, y, facecolor='none')

# get the extent of the axes
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()

# create a dummy image
img_data = np.arange(ymin,ymax,(ymax-ymin)/100.)
img_data = img_data.reshape(img_data.size,1)

# plot and clip the image
im = ax.imshow(img_data, aspect='auto', origin='lower', cmap=plt.cm.Reds_r, extent=[xmin,xmax,ymin,ymax], vmin=y.min(), vmax=30.)

im.set_clip_path(poly)

The image is given an extent which basically stretches it over the entire axes. Then the clip_path makes it only showup where the fill polygon is drawn.

enter image description here




回答2:


I think all you need is to do the plot of the data one at a time, like:

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

    # Create fake data
    x = numpy.linspace(0,4)
    y = numpy.exp(x)

    # Now plot one by one
    bar_width = x[1] - x[0]  # assuming x is linealy spaced
    for pointx, pointy in zip(x,y):
        current_color = cm.jet( min(pointy/30, 30)) # maximum of 30
        plt.bar(pointx, pointy, bar_width, color = current_color)       

    plt.show()

Resulting in: enter image description here



来源:https://stackoverflow.com/questions/19132402/set-a-colormap-under-a-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!