1
votes

I'd like to color the line of a 2D-Plot. I want the coloring to be a function of x. Say

f(x)=x^2

I want to produce a plot where the color of f(x) ranges from red to blue, depending on a function g(x), say

g(x)=x

If g(x)=10, f(x) should be blue, if g(x)=0, f should be colored red. In between I need a smooth transition between the two colors.

Any help, idea or query would be greatly appreciated, thanks!

1

1 Answers

0
votes

When plotting points, Gnuplot supports the lc variable option which allows to specify the linetypes (and thus colors) for individual points. However, with the lines plotting style (and a color gradient along the line being plotted), one has to most likely digress to an alternative strategy. For example, one could divide the x-range into independent segments, for each segment calculate the corresponding color (in terms of your function g(x)) and finally plot f(x) on each of the segments independently:

set terminal pngcairo rounded enhanced font ",16"
set output 'test.png'
set size ratio 2/(1+sqrt(5.))

unset key

xMin = 0.0
xMax = 10.0

set xr [xMin:xMax]
set yr [0:100]

#coloring function, gMin/gMax has to be set accordingly
#so that the scaled function h(x) does not overflow the [0,1] interval
gMin = 0.
gMax = +10.
g(x) = x

#function to be plotted
f(x) = x*x

#coloring function rescaled into interval [0,1]
#for each g(x), gMin/gMax should be adjusted correspondingly
h(x) = (g(x) - gMin)/(gMax - gMin)

#generate RGB representation of the interpolated color
#corresponding to the red (gMin) -> blue (gMax) transition
color(x) = sprintf('#%02X00%02X', (1-h(x))*255, h(x)*255);

#divide the x range into N segments
N = 200
dx = (xMax - xMin)/N

set samples 1000

#make the segments overlap a bit so that we don't need too high "samples"
eps = dx/10

#plot each segment with corresponding color 
binLeftBorder(i) = xMin + i*dx
binMidPoint(i) = (binLeftBorder(i) + binLeftBorder(i+1))/2

isInBin(i, x) = (x >= (binLeftBorder(i) - eps) && x < (binLeftBorder(i+1) + eps))

plot for [i=0:N-1] isInBin(i, x)?f(x):(1/0) w l \
    lw 4 lc rgb color(binMidPoint(i))

This would produce: enter image description here