Plotting by multiple factors

Hi all,

I have a dataset with three factors and one dependent variable. In the example below, how do I get all of the linear data in the top plot and all of the exponential data in the bottom plot. I tried changing the order of variables in group, but to no avail.

Example

example

Code

using StatsPlots, DataFrames

linear(x, β0, β1) = β0 + β1 * x

exponential(x, β, λ) = β * exp(λ * x)

xs = 1:10

np1 = [(p1,p2,x,y = linear(x, p1, p2)) for p1 in [0.0,1.0] for p2 in [.2,.6] for x in xs]

df = DataFrame(np1)
df[!,:function] .= "linear"

np2 = [(p1,p2,x,y = exponential(x, p1, p2)) for p1 in [.0002,.0003] for p2 in [1.0,1.1] for x in xs]
temp =  DataFrame(np2)
temp[!,:function] .= "exponential"

append!(df, temp)

@df df plot(:x, :y, group=(:p1,:p2,:function), layout=(2,1), ylims=(0,20))

You can use grouped dataframes and loop over these.
As there are only two groups in your example, the code below writes it explicitly without a loop:

gdf = groupby(df, :function)
fig = plot(layout=(2,1), legend=:topleft)
@df gdf[1] plot!(fig[1],:x, :y, group=(:function, :p1, :p2), ylims=(0,20))
@df gdf[2] plot!(fig[2],:x, :y, group=(:function, :p1, :p2), ylims=(0,20))

StatsPlots_grouped_plots

1 Like

Thank you for your solution. This is a good workaround.

I wonder if it would be possible to add a feature to StatsPlots that organizes the factors based on the layout and group arguments. I suppose it might be hard to generalize a pattern.

Someone more knowledgeable should advise.
At any rate, do not see harm in opening an issue at StatsPlots.jl, in case there is really one and improvements can be made as you suggest.

I opened an issue. Thanks again for your help!

1 Like