Pyplot: vertical gradient fill under curve?

丶灬走出姿态 提交于 2019-11-26 22:18:28

问题


I'm wondering if there's a way to fill under a pyplot curve with a vertical gradient, like in this quick mockup:

I found this hack on StackOverflow, and I don't mind the polygons if I could figure out how to make the color map vertical: How to fill rainbow color under a curve in Python matplotlib


回答1:


There may be a better way, but here goes:

from matplotlib import pyplot as plt

x = range(10)
y = range(10)
z = [[z] * 10 for z in range(10)]
num_bars = 100  # more bars = smoother gradient

plt.contourf(x, y, z, num_bars)

background_color = 'w'
plt.fill_between(x, y, y2=max(y), color=background_color)

plt.show()

Shows:




回答2:


There is an alternative solution closer to the sketch in the question. It's given on Henry Barthes' blog http://pradhanphy.blogspot.com/2014/06/filling-between-curves-with-color.html. This applies an imshow to each of the patches, I've copied the code in case the link changes,

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch

xx=np.arange(0,10,0.01)
yy=xx*np.exp(-xx)

path = Path(np.array([xx,yy]).transpose())
patch = PathPatch(path, facecolor='none')
plt.gca().add_patch(patch)

im = plt.imshow(xx.reshape(yy.size,1),   
                cmap=plt.cm.Reds,
                interpolation="bicubic",
                origin='lower',
                extent=[0,10,-0.0,0.40],
                aspect="auto",
                clip_path=patch, 
                clip_on=True)
plt.show()


来源:https://stackoverflow.com/questions/22081361/pyplot-vertical-gradient-fill-under-curve

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