6
votes

I'm using gnuplot for contour plot of a several function. This is for optimization problem. I have 3 functions:

  1. f(x,y)
  2. g1(x,y)
  3. g2(x,y)

both g1(x,y) and g2(x,y) are constraints and would like to plot on top of the contour plot of f(x,y).

Here is the textbook example:

enter image description here

Here is my attempt to replicate it in gnuplot, thanks to @theozh.

### contour lines with labels
reset session

f(x,y)=(x**2+y-11)**2+(x+y**2-7)**2
g1(x,y)=(x-5)**2+y**2
g2(x,y) = 4*x+y

set xrange [0:6]
set yrange [0:6]
set isosample 250, 250
set key outside

set contour base
set cntrparam levels disc 10,30,75,150,300,500,850,1500 
unset surface
set table $Contourf
    splot f(x,y)
unset table

set contour base
set cntrparam levels disc 26
unset surface
set table $Contourg1
    splot g1(x,y)
unset table

set contour base
set cntrparam levels disc 20
unset surface
set table $Contourg2
    splot g2(x,y)
unset table

set style textbox opaque noborder

set datafile commentschar " "
plot for [i=1:8] $Contourf u 1:2:(i) skip 5 index i-1 w l lw 1.5 lc var title columnheader(5)
replot $Contourg1 u 1:2:(1) skip 5 index 0 w l lw 4 lc 0 title columnheader(5)
replot $Contourg2 u 1:2:(1) skip 5 index 0 w l lw 4 lc 0 title columnheader(5)

enter image description here

I would like to replicate the textbook picture in the gnuplot example. How to do a hatch mark on the functions g1 and g2, the thick black line in plot above.

@theozh provided an excellent solution below. However, the method doesnot work for steep curves. As an example

reset session
unset key

set size square

g(x,y) = -0.8-1/x**3+y

set xrange [0:4]
set yrange [0:4]
set isosample 250, 250
set key off

set contour base
unset surface

set cntrparam levels disc 0
set table $Contourg
    splot g(x,y)
unset table

set angle degree
set datafile commentschar " "

plot $Contourg u 1:2 skip 5 index 0 w l lw 2 lc 0 title columnheader(5)

set style fill transparent pattern 4
replot $Contourg u 1:2:($2+0.2) skip 5 index 0 w filledcurves lc 0 notitle 

yields the following figure. Is there a way to use different offsets, for example offset x values for x < 1.3 and for x > 1.3 offset y values. This would yield a much better filled curve. A matlab implementations of what I was looking for can be found here: https://www.mathworks.com/matlabcentral/fileexchange/29121-hatched-lines-and-contours.

enter image description here

In replcating @Ethans program, I get the following, the dashtype is relatively thick compared to @Ethan not sure why, I'm using gnuplot v5.2 and wxt terminal.

enter image description here

When I replicate @theozh code, it works very well except for closed contours, not sure why? see below for example:

f(x,y)=x*exp(-x**2-y**2)+(x**2+y**2)/20
g1(x,y)= x*y/2+(x+2)**2+(y-2)**2/2-2

set xrange [-7:7]
set yrange [-7:7]
set isosample 250, 250
set key outside

set contour base
unset surface

set cntrparam levels disc 4,3.5,3,2.5,2,1.5,1,0.5,0 
set table $Contourf
    splot f(x,y)
unset table

set cntrparam levels disc 0
set table $Contourg1
    splot g1(x,y)
unset table

# create some extra offset contour lines
# macro for setting contour lines
ContourCreate = '\
    set cntrparam levels disc Level; \
    set table @Output; \
        splot @Input; \
    unset table'

Level = 0.45
Input = 'g1(x,y)'
Output = '$Contourg1_ext'
@ContourCreate


# Macro for ordering the datapoints of the contour lines which might be split
ContourOrder = '\
stats @DataIn skip 6 nooutput; \
N = STATS_blank-1; \
set table @DataOut; \
    do for [i=N:0:-1] { plot @DataIn u 1:2 skip 5 index 0 every :::i::i with table }; \
unset table'

DataIn = '$Contourg1'
DataOut = '$Contourg1_ord'
@ContourOrder

DataIn = '$Contourg1_ext'
DataOut = '$Contourg1_extord'
@ContourOrder


# Macro for reversing a datablock
ContourReverse = '\
set print @DataOut; \
    do for [i=|@DataIn|:1:-1] { print @DataIn[i]}; \
set print'

DataIn = '$Contourg1_extord'
DataOut = '$Contourg1_extordrev'
@ContourReverse

# Macro for adding datablocks
ContourAdd = '\
set print @DataOut; \
    do for [i=|@DataIn1|:1:-1] { print @DataIn1[i]}; \
    do for [i=|@DataIn2|:1:-1] { print @DataIn2[i]}; \
set print'

DataIn1 = '$Contourg1_ord'
DataIn2 = '$Contourg1_extordrev'
DataOut = '$Contourg1_add'
@ContourAdd


set style fill noborder 
set datafile commentschar " "
plot \
    for [i=1:8] $Contourf u 1:2:(i) skip 5 index i-1 w l lw 1.5 lc var title columnheader(5), \
    $Contourg1 u 1:2 skip 5 index 0 w l lw 2 lc 0 title columnheader(5), \
    $Contourg1_add u 1:2 w filledcurves fs transparent pattern 5 lc rgb "black" notitle

enter image description here

4
Will a dashed line not always be on both sides? As I understand, you want the hatching pattern just on one side.theozh
@theozh you are correct, I only want dashed line in one side. Your answer is giving me the correct view.forecaster

4 Answers

1
votes

Here is the solution you (and I) were hoping for. You just enter the hatch parameters: TiltAngle in degrees (>0°: left side, <0° right side in direction of curve), and HatchLength and HatchSeparation in pixels. The procedure has become a bit lengthy but it does what you want. I have tested it with gnuplot 5.2.6 and wxt and qt terminal. You need to determine the scaling factors for other terminals.

What the procedure basically does:

  1. determines the angle between two consecutive points of the data input curve
  2. interpolates datapoints along the curve according to HatchSeparation
  3. Scales everything such that is independent of graph scale and terminal size (this, however, requires a dummy plot x for getting the gnuplot variables GPVAL_X_MAX, GPVAL_X_MIN, GPVAL_TERM_XMAX, GPVAL_TERM_XMIN.

Limitations:

  • does not work (yet) with logarithmic axes
  • does not work (yet) with comment lines or empty lines in input datablock

If you are using it together with your contour lines you have to make sure that the contour line datapoints are in the right order (see comment in my first answer).

For better clarity of the code the procedure generating test circles tbCreateCircleData.gpp and the hatch pattern tbHatchLineGeneration.gpp are put into separate gnuplot procedure files. The variables in these subprocedures are prefixed with CC_ and HLG_ in order to avoid possible conflicts of variable names if you are using it with your existing main plotting routine. Have fun! Comments and improvements are welcome!

Subprocedure: "tbCreateCircleData.gpp"

### create circle data
# example usage: call "tbCreateCircleData.gpp "$OutputData" 0.5 0.5 1.0 0 360 180
# Note: negative numbers have to be put into ""
CC_outputdata  = ARG1
CC_center_x    = ARG2
CC_center_y    = ARG3
CC_radius      = ARG4
CC_angle_start = ARG5
CC_angle_end   = ARG6
CC_samples     = ARG7

set print @CC_outputdata
    do for [CC_i = 1:CC_samples] {
        CC_angle = CC_angle_start + (CC_angle_end -CC_angle_start)/(CC_samples - 1.0)*(CC_i-1)
        CC_x = CC_center_x + CC_radius*cos(CC_angle)
        CC_y = CC_center_y + CC_radius*sin(CC_angle)
        print sprintf("%f\t%f",CC_x,CC_y)
    }
set print
### end of gnuplot procedure

Subprocedure: "tbHatchLineGeneration.gpp"

### create dataset for hatch pattern
# example usage:
# call "tbHatchLineGeneration.gpp" "$Circle" "$Hatch" TiltAngle HatchLength HatchSeparation
# Note: negative numbers have to be put into ""
HLG_InputData       = ARG1
HLG_OutputData      = ARG2
HLG_TiltAngle       = ARG3
HLG_HatchLength     = ARG4
HLG_HatchSeparation = ARG5

# different terminal units per pixel
HLG_Rtupx = 1.                                   # for pngcairo terminal: 1 tu/px
if (GPVAL_TERM eq "wxt") { HLG_Rtupx = 20. }     # 20 tu/px, 20 terminal-units per pixel
if (GPVAL_TERM eq "qt")  { HLG_Rtupx = 10. }     # 10 tu/px, 10 terminal-units per pixel
# Ratio: axis units per terminal units
# print GPVAL_X_MAX, GPVAL_X_MIN, GPVAL_TERM_XMAX, GPVAL_TERM_XMIN
HLG_Rxautu = (GPVAL_X_MAX-GPVAL_X_MIN)/(GPVAL_TERM_XMAX-GPVAL_TERM_XMIN)
HLG_Ryautu = (GPVAL_Y_MAX-GPVAL_Y_MIN)/(GPVAL_TERM_YMAX-GPVAL_TERM_YMIN)

# Angle by dx,dy (range: -90°<= angle < 270°), NaN if dx=dy=0
HLG_Angle(dx,dy) = dx==0 ? (dy==0 ? NaN : sgn(dy)*90) : dx<0 ? 180+atan(dy/dx) : atan(dy/dx)

HLG_dx_px(n) = HLG_dx/HLG_Rxautu/HLG_Rtupx
HLG_dy_px(n) = HLG_dy/HLG_Ryautu/HLG_Rtupx
HLG_length_px(n) = sqrt(HLG_dx_px(n)**2 + HLG_dy_px(n)**2)

# create path data with 4 columns: x y cumulated_length angle
HLG_x1 = HLG_y1 = NaN
HLG_PathLength = 0
set table $HLG_Path
    plot @HLG_InputData u \
    (HLG_x0=HLG_x1,HLG_x1=$1,HLG_dx=HLG_x1-HLG_x0,$1): \
    (HLG_y0=HLG_y1,HLG_y1=$2,HLG_dy=HLG_y1-HLG_y0,$2): \
    ($0>0?HLG_PathLength=HLG_PathLength+HLG_length_px(0):HLG_PathLength): \
    (HLG_Angle(HLG_dx,HLG_dy)): (HLG_dx) : (HLG_dy) w table
unset table
# print $HLG_Path
HLG_Resamples = HLG_PathLength/HLG_HatchSeparation          # density of hatch lines

# resample data in equidistant steps along the length of the path
HLG_x0(n) = real(word(@HLG_InputData[n],1))
HLG_y0(n) = real(word(@HLG_InputData[n],2))
HLG_r0(n) = real(word($HLG_Path[n],3))
HLG_a0(n) = n+1>|$HLG_Path| ? real(word($HLG_Path[n],4)) : real(word($HLG_Path[n+1],4))
HLG_Frac(n) = (HLG_ri-HLG_r0(n))/(HLG_r0(n+1)-HLG_r0(n))

# hatch line start point
HLG_hsx(n) = HLG_x0(n) + HLG_Frac(n)*(HLG_x0(n+1)-HLG_x0(n))
HLG_hsy(n) = HLG_y0(n) + HLG_Frac(n)*(HLG_y0(n+1)-HLG_y0(n))
# delta x,y scaled  
HLG_dx_px(n) = cos(HLG_a0(n))/HLG_Rxautu*HLG_Rtupx
HLG_dy_px(n) = sin(HLG_a0(n))/HLG_Ryautu*HLG_Rtupx
HLG_AngleNew(n) = HLG_Angle(HLG_dx_px(n),HLG_dy_px(n))+HLG_TiltAngle
HLG_dx2_px(n) = cos(HLG_AngleNew(n))*HLG_Rxautu
HLG_dy2_px(n) = sin(HLG_AngleNew(n))*HLG_Ryautu
HLG_L2_px(n) = HLG_HatchLength*sqrt(HLG_dx2_px(n)**2 + HLG_dy2_px(n)**2)
HLG_AngleNew2(n) = HLG_Angle(HLG_dx2_px(n),HLG_dy2_px(n))
HLG_hlx(n) = HLG_L2_px(n) * cos(HLG_AngleNew2(n))*HLG_Rtupx
HLG_hly(n) = HLG_L2_px(n) * sin(HLG_AngleNew2(n))*HLG_Rtupx

# generate hatch lines output datablock
set print @HLG_OutputData
    HLG_j = 1
    do for [HLG_i=1:HLG_Resamples] {
        HLG_ri = (HLG_i-1)*HLG_PathLength/(HLG_Resamples-1)
        while ( !(HLG_r0(HLG_j+1) > HLG_ri) && HLG_j<|$HLG_Path|-1) { HLG_j=HLG_j+1 }
        print sprintf("%.4f\t%.4f\t%.4f\t%.4f\t%.4f", HLG_hsx(HLG_j), HLG_hsy(HLG_j), HLG_hlx(HLG_j), HLG_hly(HLG_j), HLG_a0(HLG_j) )
    }
set print
### end of gnuplot procedure

Code:

### Add hatch pattern to a curve
reset session
set term wxt size 720,360
set angle degree
unset key

set xrange[0:5]
set yrange[-1.2:1.2]

# plot some dummy to get the gnuplot variables: 
# GPVAL_X_MAX, GPVAL_X_MIN, GPVAL_TERM_XMAX, GPVAL_TERM_XMIN
plot x

# Circle parameters:
# CenterX, CenterY, Radius, StartAngle, StopAngle, NoOfDatapoints
# Note: negative numbers need to be put into ""
call "tbCreateCircleData.gpp" "$Circle01" 1.0   0.3  0.6 0 360 120
call "tbCreateCircleData.gpp" "$Circle02" 2.4   0.3  0.6 0 360 120
call "tbCreateCircleData.gpp" "$Circle03" 3.8   0.3  0.6 0 360 120
call "tbCreateCircleData.gpp" "$Circle04" 1.7 "-0.3" 0.6 0 360 120
call "tbCreateCircleData.gpp" "$Circle05" 3.1 "-0.3" 0.6 0 360 120

# Hatch parameters:
# $InputData       data you want to add hatched lines
# $OutputData      data containing the hatched lines
# TiltAngle        >0°: left side, <0° right side
# HatchLength      length in pixels
# HatchSeparation  separation of hatch lines in pixels
# "$InputData", "$OutputData", TiltAngle, HatchLength, HatchSeparation
# Note: negative numbers have to be put into ""
call "tbHatchLineGeneration.gpp" "$Circle01" "$Hatch01" "-90" 10  5
call "tbHatchLineGeneration.gpp" "$Circle02" "$Hatch02" "-30" 15 10
call "tbHatchLineGeneration.gpp" "$Circle03" "$Hatch03"   90   5  3
call "tbHatchLineGeneration.gpp" "$Circle04" "$Hatch04"   45  25 12
call "tbHatchLineGeneration.gpp" "$Circle05" "$Hatch05" "-60" 10  7

plot \
    $Circle01 u 1:2 w l lc rgb "web-blue", \
    $Hatch01 u 1:2:3:4 w vec lw 1 lc rgb "web-blue" nohead, \
    $Circle02 u 1:2 w l lc rgb "black", \
    $Hatch02 u 1:2:3:4 w vec lw 1 lc rgb "black" nohead, \
    $Circle03 u 1:2 w l lc rgb "red", \
    $Hatch03 u 1:2:3:4 w vec lw 1 lc rgb "red" nohead, \
    $Circle04 u 1:2 w l lc rgb "yellow", \
    $Hatch04 u 1:2:3:4 w vec lw 1 lc rgb "yellow" nohead, \
    $Circle05 u 1:2 w l lc rgb "web-green", \
    $Hatch05 u 1:2:3:4 w vec lw 1 lc rgb "web-green" nohead

### end of code

Result:

enter image description here

3
votes

Another possibility is to use a custom dash pattern, as shown below: By the way, it is almost never correct to use "replot" to compose a single figure.

# Additional contour levels displaced by 0.2 from the original
set contour base
set cntrparam levels disc 20.2
unset surface
set table $Contourg2d
    splot g2(x,y)
unset table

set contour base
set contour base
set cntrparam levels disc 26.2
unset surface
set table $Contourg1d
    splot g1(x,y)
unset table

set linetype 101 lc "black" linewidth 5 dashtype (0.5,5)

plot for [i=1:8] $Contourf u 1:2:(i) skip 5 index i-1 w l lw 1.5 lc var title columnheader(5), \
        $Contourg1 u 1:2:(1) skip 5 index 0 w l lw 1 lc "black" title columnheader(5), \
        $Contourg2 u 1:2:(1) skip 5 index 0 w l lw 1 lc "black" title columnheader(5), \
        $Contourg1d u 1:2:(1) skip 5 index 0 w l linetype 101 notitle, \
        $Contourg2d u 1:2:(1) skip 5 index 0 w l linetype 101 notitle

enter image description here

Amended to show use of contours offset so that the dashes are only on one side of the line.

2
votes

If you really want to have good hatch marks, you can draw a whole lot of arrows with no heads.

The example below computes the locations and slopes of each hatch mark in the loop making them nearly perpendicular to the drawn line (to numerical accuracy). It also spaces them along the line (again to rudimentary numerical accuracy but for a plot it is more than good enough.

reset
set grid
set sample 1000

set xrange [0:6]
set yrange [0:6]

# First, plot the actual curve
plot 1/log(x)

# Choose a length for your hatch marks, this will 
# depend on your axis scale.
Hlength = 0.2

# Choose a distance along the curve for the hatch marks. Again
# will depend on you axis scale.
Hspace = 0.5

# Identify one end of the curve on the plot, set x location for
# first hatch mark.
# For this case, it is when 1/log(x) = 4
x1point = exp(0.25)
y1point = 1/log(x1point)

# Its just easier to guess how many hatch marks you need instead
# of trying to compute the length of the line.
do for [loop=1:14] {

# Next, find the slope of the function at this point.
# If you have the exact derivative, use that.
# This example assumes you perhaps have a user defined funtion
# that is likely too difficult to get a derivative so it 
# increments x by a small amount to numerically compute it
slope = (1/log(x1point+0.001)-y1point)/(0.001)
#slopeAng = atan2(slope)
slopeAng = atan2((1/log(x1point+.001)-y1point),0.001)

# Also find the perpendicular to this slope
perp = 1/slope
# Get angle of perp from horizontal
perpAng = atan(perp)


# Draw a small hatch mark at this point
x2point = x1point + Hlength*cos(perpAng)
y2point = y1point - Hlength*sin(perpAng)
# The hatch mark is just an arrow with no heads
set arrow from x1point,y1point to x2point,y2point nohead

# Move along the curve approximately a distance of Hspace
x1point = x1point + Hspace*cos(slopeAng)
y1point = 1/log(x1point)

# loop around to do next hatch mark
}

replot

You will get something like this enter image description here

Note that you can easily adjust the hatch mark length and the spacing between them. Also, if your x and y axis have significantly different scales, it would not be too hard to scale the x or y length of the arrow so they 'look' like equal lengths.


Edit:

You have the added complication of doing a contour plot. I've completed what you need to do. I resolved your g1 and g2 functions at the contour level you wanted the constraints and named two new functions g1_26 and g2_20 and solved for y for each.

I also discoverd that the hatch marks change sides with the simple program above when the sign of the slope changes so I added the sgn(slope) when calculating the x2 and y2 points of the hatch mark and also added a flip variable so you can easily control which side of the line the hatch marks are drawn. Here is the code:

### contour lines with labels
reset session

f(x,y)=(x**2+y-11)**2+(x+y**2-7)**2
g1(x,y)=(x-5)**2+y**2
g2(x,y) = 4*x+y

set xrange [0:6]
set yrange [0:6]
set isosample 250, 250
set key outside

set contour base
set cntrparam levels disc 10,30,75,150,300,500,850,1500 
unset surface
set table $Contourf
    splot f(x,y)
unset table

set contour base
set cntrparam levels disc 26
unset surface
set table $Contourg1
    splot g1(x,y)
unset table

set contour base
set cntrparam levels disc 20
unset surface
set table $Contourg2
    splot g2(x,y)
unset table

set style textbox opaque noborder

set datafile commentschar " "
plot for [i=1:8] $Contourf u 1:2:(i) skip 5 index i-1 w l lw 1.5 lc var title columnheader(5)
replot $Contourg1 u 1:2:(1) skip 5 index 0 w l lw 4 lc 0 title columnheader(5)
replot $Contourg2 u 1:2:(1) skip 5 index 0 w l lw 4 lc 0 title columnheader(5)

###############################
# Flip should be -1 or 1 depending on which side you want hatched.
flip = -1

# put hatches on g1
# Since your g1 constraint is at g1(x,y) = 26, lets
# get new formula for this specific line.
#g1(x,y)=(x-5)**2+y**2 = 26
g1_26(x) = sqrt( -(x-5)**2 + 26)

# Choose a length for your hatch marks, this will 
# depend on your axis scale.
Hlength = 0.15

# Choose a distance along the curve for the hatch marks. Again
# will depend on you axis scale.
Hspace = 0.2

# Identify one end of the curve on the plot, set x location for
# first hatch mark.
x1point = 0
y1point = g1_26(x1point)

# Its just easier to guess how many hatch marks you need instead
# of trying to compute the length of the line.
do for [loop=1:41] {

# Next, find the slope of the function at this point.
# If you have the exact derivative, use that.
# This example assumes you perhaps have a user defined funtion
# that is likely too difficult to get a derivative so it 
# increments x by a small amount to numerically compute it
slope = (g1_26(x1point+0.001)-y1point)/(0.001)
#slopeAng = atan2(slope)
slopeAng = atan2((g1_26(x1point+.001)-y1point),0.001)

# Also find the perpendicular to this slope
perp = 1/slope
# Get angle of perp from horizontal
perpAng = atan(perp)


# Draw a small hatch mark at this point
x2point = x1point + flip*sgn(slope)*Hlength*cos(perpAng)
y2point = y1point - flip*sgn(slope)*Hlength*sin(perpAng)
# The hatch mark is just an arrow with no heads
set arrow from x1point,y1point to x2point,y2point nohead lw 2

# Move along the curve approximately a distance of Hspace
x1point = x1point + Hspace*cos(slopeAng)
y1point = g1_26(x1point)

# loop around to do next hatch mark
}

###############################
# Flip should be -1 or 1 depending on which side you want hatched.
flip = -1

# put hatches on g2
# Since your g2 constraint is at g2(x,y) = 20, lets
# get new formula for this specific line.
#g2(x,y) = 4*x+y = 20
g2_20(x) = 20 - 4*x

# Choose a length for your hatch marks, this will 
# depend on your axis scale.
Hlength = 0.15

# Choose a distance along the curve for the hatch marks. Again
# will depend on you axis scale.
Hspace = 0.2

# Identify one end of the curve on the plot, set x location for
# first hatch mark.
x1point =3.5
y1point = g2_20(x1point)

# Its just easier to guess how many hatch marks you need instead
# of trying to compute the length of the line.
do for [loop=1:32] {

# Next, find the slope of the function at this point.
# If you have the exact derivative, use that.
# This example assumes you perhaps have a user defined funtion
# that is likely too difficult to get a derivative so it 
# increments x by a small amount to numerically compute it
slope = (g2_20(x1point+0.001)-y1point)/(0.001)
slopeAng = atan2((g2_20(x1point+.001)-y1point),0.001)

# Also find the perpendicular to this slope
perp = 1/slope
# Get angle of perp from horizontal
perpAng = atan(perp)


# Draw a small hatch mark at this point
x2point = x1point + flip*sgn(slope)*Hlength*cos(perpAng)
y2point = y1point - flip*sgn(slope)*Hlength*sin(perpAng)
# The hatch mark is just an arrow with no heads
set arrow from x1point,y1point to x2point,y2point nohead lw 2

# Move along the curve approximately a distance of Hspace
x1point = x1point + Hspace*cos(slopeAng)
y1point = g2_20(x1point)

# loop around to do next hatch mark
}

replot

Here is the result:

enter image description here

2
votes

I'm not aware of a feature in gnuplot which would generate such hatched lines. One workaround could be the following: shift your curves slightly by some value and fill it with filledcurves and a hatch pattern. However, this works only well if the curve is a straight line or not too much bent. Unfortunately, there is also only a very limited number of hatch patterns in gnuplot (see Hatch patterns in gnuplot) and they are not customizable. You need to play with the shift value and the hatched fill pattern.

Code:

### contour lines with hatched side
reset session

f(x,y)=(x**2+y-11)**2+(x+y**2-7)**2
g1(x,y)=(x-5)**2+y**2
g2(x,y) = 4*x+y

set xrange [0:6]
set yrange [0:6]
set isosample 250, 250
set key outside

set contour base
unset surface

set cntrparam levels disc 10,30,75,150,300,500,850,1500 
set table $Contourf
    splot f(x,y)
unset table

set cntrparam levels disc 26
set table $Contourg1
    splot g1(x,y)
unset table

set cntrparam levels disc 20
set table $Contourg2
    splot g2(x,y)
unset table
set angle degree
set datafile commentschar " "
plot for [i=1:8] $Contourf u 1:2:(i) skip 5 index i-1 w l lw 1.5 lc var title columnheader(5)
replot $Contourg1 u 1:2 skip 5 index 0 w l lw 4 lc 0 title columnheader(5)
replot $Contourg2 u 1:2 skip 5 index 0 w l lw 4 lc 0 title columnheader(5)

set style fill transparent pattern 5
replot $Contourg1 u 1:2:($2+0.2) skip 5 index 0 w filledcurves lc 0 notitle
set style fill transparent pattern 4
replot $Contourg2 u 1:2:($2+0.5) skip 5 index 0 w filledcurves lc 0 notitle
### end of code

Result:

enter image description here

Addition:

With gnuplot you will probably find a workaround most of the times. It's just a matter how complicated or ugly you allow it to become. For such steep functions use the following "trick". The basic idea is simple: take the original curve and the shifted one and combine these two curves and plot them as filled. But you have to reverse one of the curves (similar to what I already described earlier: https://stackoverflow.com/a/53769446/7295599).

However, here, a new "problem" arises. For whatever reason, the contour line data consist out of several blocks separated by an empty line and it's not a continous sequence in x. I don't know why but that's the contour lines gnuplot creates. To get the order right, plot the data into a new datablock $ContourgOnePiece starting from the last block (every :::N::N)to the first block (every :::0::0). Determine the number of these "blocks" by stats $Contourg and STATS_blank. Do the same thing for the shifted contour line into $ContourgShiftedOnePiece. Then combine the two datablocks by printing them line by line to a new datablock $ClosedCurveHatchArea, where you actually reverse one of them. This procedure will work OK for strictly monotonous curves, but I guess you will get problems with oscillating or closed curves. But I guess there might be also some other weird workarounds. I admit, this is not a "clean" and "robust" solution, but it somehow works.

Code:

### lines with one hatched side
reset session
set size square

g(x,y) = -0.8-1/x**3+y

set xrange [0:4]
set yrange [0:4]
set isosample 250, 250
set key off

set contour base
unset surface

set cntrparam levels disc 0
set table $Contourg
    splot g(x,y)
unset table

set angle degree
set datafile commentschar " "

# determine how many pieces $Contourg has
stats $Contourg skip 6 nooutput  # skip 6 lines
N = STATS_blank-1                # number of empty lines

set table $ContourgOnePiece
    do for [i=N:0:-1] {
        plot $Contourg u 1:2 skip 5 index 0 every :::i::i with table
    }
unset table
# do the same thing with the shifted $Contourg
set table $ContourgShiftedOnePiece
    do for [i=N:0:-1] {
        plot $Contourg u ($1+0.1):($2+0.1):2 skip 5 index 0 every :::i::i with table
    }
unset table
# add the two curves but reverse the second of them
set print $ClosedCurveHatchArea append
    do for [i=1:|$ContourgOnePiece|:1] {
        print $ContourgOnePiece[i]
    }
    do for [i=|$ContourgShiftedOnePiece|:1:-1] {
        print $ContourgShiftedOnePiece[i]
    }
set print

plot $Contourg u 1:2 skip 5 index 0 w l lw 2 lc 0 title columnheader(5)
set style fill transparent pattern 5 noborder
replot $ClosedCurveHatchArea u 1:2 w filledcurves lc 0
### end of code

Result:

enter image description here

Addition 2:

Actually, I like @Ethan's approach of creating an extra level contour line. This works well as long as the gradient is not too large. Otherwise you might get noticeable deformations of the second contour line (see red curve below). However, in the above examples with g1 and g2 you won't notice a difference. Another advantages is that the hatch lines are perpendicular to the curve. A disadvantage is that you might get some interruptions of the regular pattern.

The solution with a small shift of the original curve in x and/or y and filling areas doesn't work with oscillating or closed lines.

Below, the black hatched curves are a mix of these approaches.

Procedure:

  1. create a single contour line
  2. create an extended (ext) or shifted (shf) contourline (either by a new contour value or by shifting an existing one)
  3. order the contour line (ord)
  4. reverse the contour lin (rev)
  5. add the ordered (ord) and the extended,ordered,reversed (extordrev)
  6. plot the added contour line (add) with filledcuves

NB: if you want to shift a contour line by x,y you have to order first and then shift it, otherwise the macro @ContourOrder cannot order it anymore.

You see, it can get complicated. In summary, so far there are three approaches:

(a) extra level contour line and thick dashed line (@Ethan)

pro: short, works for oscillating and closed curves; con: bad if large gradient

(b) x,y shifted contour line and hatched filledcurves (@theozh)

pro: few parameters, clear picture; con: lengthy, only 4 hatch patterns)

(c) derivative of data point (@Dan Sp.)

pro: possibly flexibility for tilted hatch patterns; con: need of derivative (numerical if no function but datapoints), pattern depends on scale

The black curves are actually a mix of (a) and (b). The blue curve is (b). Neither (a) nor (b) will work nicely on the red curve. Maybe (c)? You could think of further mixing the approaches... but this probably gets also lengthy.

Code:

### contour lines with hashed side
set term wxt butt
reset session

f(x,y)=(x**2+y-11)**2+(x+y**2-7)**2
g1(x,y)=(x-5)**2+y**2
g2(x,y) = 4*x+y
g3(x,y) = -0.8-1/x**3+y

set xrange [0:6]
set yrange [0:6]
set isosample 250, 250
set key outside

set contour base
unset surface

set cntrparam levels disc 10,30,75,150,300,500,850,1500 
set table $Contourf
    splot f(x,y)
unset table

set cntrparam levels disc 26
set table $Contourg1
    splot g1(x,y)
unset table

set cntrparam levels disc 20
set table $Contourg2
    splot g2(x,y)
unset table

set cntrparam levels disc 0
set table $Contourg3
    splot g3(x,y)
unset table


# create some extra offset contour lines
# macro for setting contour lines
ContourCreate = '\
    set cntrparam levels disc Level; \
    set table @Output; \
        splot @Input; \
    unset table'

Level = 27.5
Input = 'g1(x,y)'
Output = '$Contourg1_ext'
@ContourCreate

Level = 20.5
Input = 'g2(x,y)'
Output = '$Contourg2_ext'
@ContourCreate

Level = 10
Input = 'f(x,y)'
Output = '$Contourf0'
@ContourCreate

Level = 13
Input = 'f(x,y)'
Output = '$Contourf0_ext'
@ContourCreate


# Macro for ordering the datapoints of the contour lines which might be split
ContourOrder = '\
stats @DataIn skip 6 nooutput; \
N = STATS_blank-1; \
set table @DataOut; \
    do for [i=N:0:-1] { plot @DataIn u 1:2 skip 5 index 0 every :::i::i with table }; \
unset table'

DataIn = '$Contourg1'
DataOut = '$Contourg1_ord'
@ContourOrder

DataIn = '$Contourg1_ext'
DataOut = '$Contourg1_extord'
@ContourOrder

DataIn = '$Contourg2'
DataOut = '$Contourg2_ord'
@ContourOrder

DataIn = '$Contourg2_ext'
DataOut = '$Contourg2_extord'
@ContourOrder

DataIn = '$Contourg3'
DataOut = '$Contourg3_ord'
@ContourOrder

set table $Contourg3_ordshf
    plot $Contourg3_ord u ($1+0.15):($2+0.15) w table   # shift the curve
unset table

DataIn = '$Contourf0'
DataOut = '$Contourf0_ord'
@ContourOrder

DataIn = '$Contourf0_ext'
DataOut = '$Contourf0_extord'
@ContourOrder

# Macro for reversing a datablock
ContourReverse = '\
set print @DataOut; \
    do for [i=|@DataIn|:1:-1] { print @DataIn[i]}; \
set print'

DataIn = '$Contourg1_extord'
DataOut = '$Contourg1_extordrev'
@ContourReverse

DataIn = '$Contourg2_extord'
DataOut = '$Contourg2_extordrev'
@ContourReverse

DataIn = '$Contourg3_ordshf'
DataOut = '$Contourg3_ordshfrev'
@ContourReverse

DataIn = '$Contourf0_extord'
DataOut = '$Contourf0_extordrev'
@ContourReverse

# Macro for adding datablocks
ContourAdd = '\
set print @DataOut; \
    do for [i=|@DataIn1|:1:-1] { print @DataIn1[i]}; \
    do for [i=|@DataIn2|:1:-1] { print @DataIn2[i]}; \
set print'

DataIn1 = '$Contourg1_ord'
DataIn2 = '$Contourg1_extordrev'
DataOut = '$Contourg1_add'
@ContourAdd

DataIn1 = '$Contourg2_ord'
DataIn2 = '$Contourg2_extordrev'
DataOut = '$Contourg2_add'
@ContourAdd

DataIn1 = '$Contourg3_ord'
DataIn2 = '$Contourg3_ordshfrev'
DataOut = '$Contourg3_add'
@ContourAdd

DataIn1 = '$Contourf0_ord'
DataIn2 = '$Contourf0_extordrev'
DataOut = '$Contourf0_add'
@ContourAdd

set style fill noborder 
set datafile commentschar " "
plot \
    for [i=1:8] $Contourf u 1:2:(i) skip 5 index i-1 w l lw 1.5 lc var title columnheader(5), \
    $Contourg1 u 1:2 skip 5 index 0 w l lw 3 lc 0 title columnheader(5), \
    $Contourg2 u 1:2 skip 5 index 0 w l lw 3 lc 0 title columnheader(5), \
    $Contourg3 u 1:2 skip 5 index 0 w l lw 3 lc 0 title columnheader(5), \
    $Contourg1_add u 1:2 w filledcurves fs transparent pattern 4 lc rgb "black" notitle, \
    $Contourg2_add u 1:2 w filledcurves fs transparent pattern 5 lc rgb "black" notitle, \
    $Contourg3_add u 1:2 w filledcurves fs transparent pattern 5 lc rgb "blue" notitle, \
    $Contourf0_add u 1:2 w filledcurves fs transparent pattern 6 lc rgb "red" notitle, \
### end of code

Result:

enter image description here

Addition 3:

If you plot a line with filledcurves, I guess gnuplot will connect the first and last point with a straight line and fills the enclosed area. In your circle/ellipse example the outer curve is cut at the top border of the graph. I guess that's why the script does not work in this case. You have to identify these points where the outer curve starts and ends and arrange your connected curve such that these points will be the start and end point. You see it's getting complicated...

The following should illustrate how it should work: make one curve where you start e.g. with the inner curve from point 1 to 100, then add point 1 of inner curve again, continue with point 1 of outer curve (which has opposite direction) to point 100 and add point 1 of outer curve again. Then gnuplot will close the curve by connecting point 1 of outer curve with point 1 of inner curve. Then plot it as filled with hatch pattern.

enter image description here

By the way, if you change your function g1(x,y) to g1(x,y)= x*y/2+(x+2)**2+(y-1.5)**2/2-2 (note the difference y-1.5 instead of y-2) everything works fine. See below.

Code:

### Hatching on a closed line
reset session

f(x,y)=x*exp(-x**2-y**2)+(x**2+y**2)/20
g1(x,y)= x*y/2+(x+2)**2+(y-1.5)**2/2-2

set xrange [-7:7]
set yrange [-7:7]
set isosample 250, 250
set key outside

set contour base
unset surface

set cntrparam levels disc 4,3.5,3,2.5,2,1.5,1,0.5,0 
set table $Contourf
    splot f(x,y)
unset table

set cntrparam levels disc 0
set table $Contourg1
    splot g1(x,y)
unset table

# create some extra offset contour lines
# macro for setting contour lines
ContourCreate = '\
    set cntrparam levels disc Level; \
    set table @Output; \
        splot @Input; \
    unset table'

Level = 1
Input = 'g1(x,y)'
Output = '$Contourg1_ext'
@ContourCreate

# Macro for ordering the datapoints of the contour lines which might be split
ContourOrder = '\
    stats @DataIn skip 6 nooutput; \
    N = STATS_blank-1; \
    set table @DataOut; \
        do for [i=N:0:-1] { plot @DataIn u 1:2 skip 5 index 0 every :::i::i with table }; \
    unset table'

DataIn = '$Contourg1'
DataOut = '$Contourg1_ord'
@ContourOrder

DataIn = '$Contourg1_ext'
DataOut = '$Contourg1_extord'
@ContourOrder

# Macro for reversing a datablock
ContourReverse = '\
set print @DataOut; \
    do for [i=|@DataIn|:1:-1] { print @DataIn[i]}; \
set print'

DataIn = '$Contourg1_extord'
DataOut = '$Contourg1_extordrev'
@ContourReverse

# Macro for adding datablocks
ContourAdd = '\
set print @DataOut; \
    do for [i=|@DataIn1|:1:-1] { print @DataIn1[i]}; \
    do for [i=|@DataIn2|:1:-1] { print @DataIn2[i]}; \
set print'

DataIn2 = '$Contourg1_ord'
DataIn1 = '$Contourg1_extordrev'
DataOut = '$Contourg1_add'
@ContourAdd

set style fill noborder 
set datafile commentschar " "
plot \
    for [i=1:8] $Contourf u 1:2:(i) skip 5 index i-1 w l lw 1.5 lc var title columnheader(5), \
    $Contourg1 u 1:2 skip 5 index 0 w l lw 2 lc 0 title columnheader(5), \
    $Contourg1_add u 1:2 w filledcurves fs transparent pattern 5 lc rgb "black" notitle
### end of code

Result:

enter image description here