Reputation: 6331
I have a strange situation which I would like a bit of assistance. I have the following data:
xdata = [ 11.125, 11.375, 11.625, 11.875, 12.125, 12.375, 12.625, 12.875, 13.125, 13.375, 13.625, 13.875, 14.125, 14.375, 14.625, 14.875, 15.125, 15.375]
ydata = [ 5.49305494, 6.51732366, 6.54733551, 6.38045781, 6.16101383, 5.93700054, 5.70674253, 5.47409529, 5.23715401, 4.98422568, 4.72124987, 4.43762374, 4.11756956, 3.74888544, 3.32613096, 2.79169065, 2.0374265, 1.07918125]
What I would like is to use the fill_between() function, such that the filled region is between two x-values which are not part of the list xdata, while at the same time fills the region between y=0, and the curve generated by the ydata provided.
I've thought of two things: 1) Not caring about being bounded by the y-data (in which case I would use the axvspan() function); this is no longer really an option, and 2) doing some sort of interpolation scheme in order to find the interpolated ydata values for which the x values I have (which again are not part of xdata). If I do move forward with the second idea, I would need to know how matplotlib interpolates between data points by default when using the plot() function in order to try to match the curve generated by the ydata exactly.
I'm open to the interpolation idea, but I'm really open to anything that works. Thanks!
Upvotes: 2
Views: 2407
Reputation: 46530
I think you probably have to do interpolation. Even somehow "cropping" the result from
plt.fill_between(xdata, 0, ydata)
As discussed in the comments above would be equivalent to linear interpolation (straight lines between each data point). Here's how you could do it:
xdata = ...
ydata = ...
xleft, xright = 13.3979400087, 13.414973348
xfill = np.linspace(xleft, xright)
yfill = np.interp(xfill, xdata, ydata)
plt.fill_between(xfill, 0, yfill, color='r')
If you do this on top of the original, you can see it better:
Of course, you could do fancier interpolation, with a spline being the next step:
from scipy import interpolate
# same as above ...
yfill_spline = interpolate.spline(xdata, ydata, xfill) #note the different args ordering from np.interp
plt.fill_between(xfill, 0, yfill_spline, color='g')
The difference is pretty subtle for your example so I've zoomed in to the top edge of the filled region, but with higher curvature data you'll notice a difference more easily:
For comparison, see the uncropped version with linear vs spline interpolation. You'd notice a big difference between the methods if you had xleft
and xright
near the peak (11
– 12
or so).
Upvotes: 1