Hi all-

I would like to use a gradient to color code lines based on values of a factor. In the example below, I would like the two groups of lines to have the same colors based on the slopes. How do I do that?

```
using DataFrames, StatsPlots, Distributions
x = 1:10
linear(b0, b1, x) = b0 + b1*x
B0 = [0,10]
B1 = range(.5, stop=1, length=5)
y = [linear.(b0, b1, x) for b1 in B1 for b0 in B0]
y = vcat(y...)
df = DataFrame(group = repeat(0:1,inner=50), slope = repeat(repeat(B1, inner=10), outer =2),
x = repeat(x,outer=10), y = y)
@df df plot(:x, :y, group = (:group,:slope), legend=false, palette = cgrad(:viridis,:slope))
```

1 Like

Did you figure it out? Iâ€™m trying to do something similar with using a color map on the groupsâ€¦

@hdavid16, unfortunately I did not find a solution to this problem. I am still interested in a solution if someone else has one.

One more laborious way, replaces the last one-liner above (*not working as expected*) by:

```
# (continuation):
XX, YY, SL = zeros(10,10), zeros(10,10), zeros(10)
i = 1
for d in groupby(df,[:group,:slope])
XX[:,i], YY[:,i], SL[i] = d.x, d.y, d.slope[1]
i += 1
end
I = sortperm(SL)
plot(legend=false, ratio=1, xlims=extrema(x),cbar=true)
plot!(XX[I,:], YY[I,:], line_z = SL[I]')
```

Thanks! Do you suppose there is a bug in StatsPlots or was I doing something incorrectly in my original post?

Sorry, donâ€™t know those recipes enough to confirm it.

OP was just before getting a solution.

Minimal change solution:

```
using DataFrames, StatsPlots, Distributions
x = 1:10
linear(b0, b1, x) = b0 + b1*x
B0 = [0, 10]
B1 = range(.5, stop=1, length=5)
y = [linear.(b0, b1, x) for b0 in B0 for b1 in B1] # `b1 in B1` and `b0 in B0` exchanged
y = vcat(y...)
df = DataFrame(group = repeat(0:1,inner=50), slope = repeat(repeat(B1, inner=10), outer =2),
x = repeat(x,outer=10), y = y)
@df df plot(:x, :y, group = (:group,:slope), legend=false,
color = cgrad(:viridis,:slope), line_z = :slope) # palette -> color, `line_z = :slope` added
```

2 Likes

Thank you @genkuroki! I had no idea that I should pass `line_z = :slope`

as an argument.

Lol, this is embarrassing as this was one of the first things tried.

Checked the REPL history file `repl_history.jl`

just to be sure:

```
# time: 2021-08-16 15:52:31 GTB Daylight Time
# mode: julia
@df df plot(:x, :y, group = (:group,:slope), line_z=:slope, legend=false, palette = cgrad(:viridis,:slope))
```

Somehow the colors looked scrambled but cannot reproduce again. Nevermindâ€¦

1 Like

The response on slack is useful too: Slack