我正在尝试基于使用pandas和matplotlib处理的数据集的可视化问题。我将数据绘制成线图。我的目标是让曲线下面的区域用cmap进行渐变(ex' plasma')
然而,出于不同的原因,我最好的尝试都是错误的。第一个将使用渐变颜色,但仅限于线条。第二个将在线下着色,但只有纯色。我被困了很长时间......谢谢你!
ax = plot_chance_death.plot(kind='line', x = 'State', y = 'Percent Chance',
ax=ax, color='indigo')
l1 = ax.lines[0]
x1 = l1.get_ydata()
y1 = l1.get_xdata()
fig, ax = plt.subplots()
# plot only the outline of the polygon, and capture the result
poly, = ax.fill(x1, y1, 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='upper', cmap='plasma',
extent=[xmin,xmax,ymin,ymax], vmin=1., vmax=y1.max())
#this shows the gradient but above the line
im.set_clip_path(poly)
###this solution colors underneath but solid color
ax.fill_between(x1, y1, y2=0, cmap='plasma', norm=(0,.5))
答案 0 :(得分:0)
在Path
中包含要用作clip_path的区域底部是有意义的。您可以从Path
数据创建plot
,然后将两个底部点添加到其中。
import pandas as pd
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
from matplotlib.path import Path
df = pd.DataFrame({"x" : np.linspace(0,0.05,40),
"y" : np.cumsum(np.random.rand(40))[::-1]*3})
fig, ax = plt.subplots()
l, = ax.plot(df.x, df.y, color="k")
# 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='upper', cmap='plasma',
extent=[xmin,xmax,ymin,ymax], vmin=1., vmax=df.y.max())
px,py = l.get_data()
p0 = [[px[-1], py.min()], [px[0], py.min()]]
p = np.concatenate((np.c_[px,py],p0))
path = Path(p)
im.set_clip_path(path, transform=ax.transData)
plt.show()