Plotting with JuMP variables

Hello,

Not sure if i should post this here or in the visualization domain… but how can i plot a bar graph that has JuMP variables and regular Julia variables?

For example, i’m trying to plot a bargraph, like this:

Using StatPlots

b = repeat(["Before","After"], inner = 4)
p1 = groupedbar([D3_before D3_after], group = b, xlabel = "B", ylabel = "DHT3 (%)", title = "Title 1", bar_position = :dodge, bar_width=0.7)
p2 = groupedbar([DI_before DI_after], group = b, xlabel = "B", ylabel = "DHTI (%)", title = "Title 2", bar_position = :dodge, bar_width=0.7)
plot(p1,p2)

Here D3_before and DI_before are the regular Julia variables (vectors). D3_after and DI_after are the JuMP variables (vectors) that i got after solving my optimization problem. I tried to run the code, but i got an error as expected:

ERROR: LoadError: MethodError: Cannot `convert` an object of type Type{JuMP.GenericAffExpr{Float64,J
uMP.Variable}} to an object of type AbstractFloat
This may have arisen from a call to the constructor AbstractFloat(...),
since type constructors fall back to convert methods.

You can’t plot JuMP variables as they are. What you can do is plot the solution values of the JuMP variables.

So if x is your JuMP variable, call x_sol = JuMP.get_value(x) and then plot x_sol instead of x.

p.s. when posting questions like this, you should include a reproducible example. Take a read of:

1 Like

I understand, thank you!

edit: This is weird, for x i tried x_sol = JuMP.get_value(x) but i got the following error:

ERROR: LoadError: UndefVarError: get_value not defined

Then i tried the usual command i knew to get the value of a JuMP variable, x_sol = getvalue(x). The code ran fine, but it didn’t plot anything.

The only thing i see different here, is that the original Julia variable is a 4x1 Array{Float64,2}, while the new x_sol is Float64[4].