Writing a MAPLE procedure for adding the legends inside in plots - plot

How to write a procedure to add the legends of any given two functions to the suitable location in the graphs? Or we can select the location at the beginning of the procedure (like left-top, right-bottom etc.)?
For example; Let's consider the sin(x) and cos(x), and try to write a Maple code as follows:
restart:
with(plottools): with(plots):
f:=x->sin(x):
g:=x->cos(x):
A:=plot(f(x), x=0..2*3.14, style=pointline, symbol= diamond, color=red, symbolsize=11, numpoints=40, adaptive=false):
B:=plot(g(x), x=0..2*3.14, style=pointline, symbol= solidcircle, color=blue, symbolsize=11, numpoints=40, adaptive=false):
location:=0.8:
L1, L2:=line([2.75,location],[3.2,location],color=red), line([3.65,location],[4.1,location],color=blue):
P1:=plot([seq([2.75+i*(3.2-2.75)/3,location], i=1..2)],style=point,symbol= diamond, color=red, symbolsize=11):
P2:=plot([seq([3.65+i*(3.2-2.75)/3,location], i=1..2)],style=point,symbol= solidcircle, color=blue, symbolsize=11):
T:=textplot([[3.4,location,sin(x)],[4.3,location,cos(x)]]):
P:=polygon([[2.7,0.7],[2.7,0.9],[4.5,0.9],[4.5,0.7]], style=line, thickness=0):
plots:-display(A, B, P, L1, L2, T, P1, P2, scaling=constrained, size=[800,300],axes=boxed);
The image of the above code

Related

Add missing points in a 2D line represented by points in Julia

I have some 2D data in Julia representing a circular feature with some "holes" in it. I like to interpolate these holes by finding points fitting on a curve representing the shape of the feature.
Using Julia's PlotlyJS library I was able to find a nice spline interpolation curve for the points visually. However, I am not able to "access" that interpolation to calculate the actual points required. Any (alternative?) idea on how to get that?
Here is a working example in Julia:
using PlotlyJS
someData = [
3.47336 -0.471233;
3.53109 0.335963;
3.46748 1.10433;
3.13369 1.87227;
2.33268 2.51022;
1.21804 3.07551;
0.211065 3.3075;
-0.768256 3.18599;
-1.72856 2.87655;
-2.55477 2.58726;
-3.28657 1.99779;
-3.63637 1.31502;
-3.56652 -0.462201;
-2.96175 -0.956073;
-2.0519 -0.870708;
-1.07193 -0.837913;
-0.156219 -0.972855;
0.594719 -1.4576;
1.27607 -1.9387;
2.08427 -2.17288;
3.47336 -0.471233
]
plot([
scatter(
x=someData[:,1], y=someData[:,2], type="scatter", mode="markers", name="Some data",
marker=attr(size=8, color="orange", opacity=1)
),
scatter(
x=someData[:,1], y=someData[:,2], type="scatter", mode="lines", name="Plotly spline",
line=attr(color="green", width=2, shape="spline")
),
], Layout(scene=attr(aspectmode="data"), showlegend=true)
)
This was answered on the Julia Discourse here:
https://discourse.julialang.org/t/add-missing-points-in-a-2d-line/94211/3
Copy-pasting the solution (which isn't mine!):
using Dierckx, Plots
t = 1:size(data,1)
spl = ParametricSpline(t, data', bc="extrapolate", s=0.0)
tfine= range(1, size(data,1), 200)
Pfine = evaluate(spl, tfine)
t0, t1 = 12.5, 20.6
P0, P1 = evaluate.((spl,), [t0, t1])
plot(eachrow(Pfine)..., c=:blues)
scatter!(eachcol(data)...,legend=false )
scatter!([P0[1]], [P0[2]], ms=5, mc=:red)
scatter!([P1[1]], [P1[2]], ms=5, mc=:red)

Julia Flux withgradient operation

I am a newbie to Julia and Flux with some experience in Tensorflow Keras and python. I tried to use the Flux.withgradient command to write a user-defined training function with more flexibility. Here is the training part of my code:
loss, grad = Flux.withgradient(modelDQN.evalParameters) do
qEval = modelDQN.evalModel(evalInput)
Flux.mse(qEval, qTarget)
end
Flux.update!(modelDQN.optimizer, modelDQN.evalParameters, grad)
This code works just fine. But if I put the command qEval = modelDQN.evalModel(evalInput) outside the do end loop, as follows:
qEval = modelDQN.evalModel(evalInput)
loss, grad = Flux.withgradient(modelDQN.evalParameters) do
Flux.mse(qEval, qTarget)
end
Flux.update!(modelDQN.optimizer, modelDQN.evalParameters, grad)
The model parameters will not be updated. As far as I know, the do end loop works as an anonymous function that takes 0 arguments. Then why do we need the command qEval = modelDQN.evalModel(evalInput) inside the loop to get the model updated?
The short answer is that anything to be differentiated has to happen inside the (anonymous) function which you pass to gradient (or withgradient), because this is very much not a standard function call -- Zygote (Flux's auto-differentiation library) traces its execution to compute the derivative, and can't transform what it can't see.
Longer, this is Zygote's "implicit" mode, which relies on global references to arrays. The simplest use is something like this:
julia> using Zygote
julia> x = [2.0, 3.0];
julia> g = gradient(() -> sum(x .^ 2), Params([x]))
Grads(...)
julia> g[x] # lookup by objectid(x)
2-element Vector{Float64}:
4.0
6.0
If you move some of that calculation outside, then you make a new array y with a new objectid. Julia has no memory of where this came from, it is completely unrelated to x. They are ordinary arrays, not a special tracked type.
So if you refer to y in the gradient, Zygote cannot infer how this depends on x:
julia> y = x .^ 2 # calculate this outside of gradient
2-element Vector{Float64}:
4.0
9.0
julia> g2 = gradient(() -> sum(y), Params([x]))
Grads(...)
julia> g2[x] === nothing # represents zero
true
Zygote doesn't have to be used in this way. It also has an "explicit" mode which does not rely on global references. This is perhaps less confusing:
julia> gradient(x1 -> sum(x1 .^ 2), x) # x1 is a local variable
([4.0, 6.0],)
julia> gradient(x1 -> sum(y), x) # sum(y) is obviously indep. x1
(nothing,)
julia> gradient((x1, y1) -> sum(y1), x, y)
(nothing, Fill(1.0, 2))
Flux is in the process of changing to use this second form. On v0.13.9 or later, something like this ought to work:
opt_state = Flux.setup(modelDQN.optimizer, modelDQN) # do this once
loss, grads = Flux.withgradient(modelDQN.model) do m
qEval = m(evalInput) # local variable m
Flux.mse(qEval, qTarget)
end
Flux.update!(opt_state, modelDQN.model, grads[1])

Octave plot is not correctly printed in pdfcairo

I'm trying to subplot my data, but printing in PDF brings results I can't use: Title and x-axis title are cut (and the legend's box is covered by the graph, but I can handle this with other positions). I have to use gnuplot and pdfcairo because other seup isn't working with special characters, umlaut, etc.
clear;clc;close all;clf;clear all;
graphics_toolkit("gnuplot")
x = 0:.1:10;
y1 = exp(-x).*sin(x);
y2 = exp(x);
h=figure(1);
subplot(2,1,1);
plot(x,y1)
h1 = plot(x,y1);
set(h1,'LineWidth',4)
set(gca,'FontSize',32)
set(gca,'FontName','Times')
set(get(gca,'Ylabel'),'String','TTEST test \rho \rightarrow','FontWeight','Bold','FontSize',32)
set(get(gca,'Xlabel'),'String','abc / - \rightarrow','FontWeight','Bold','FontSize',32)
legend({
'h_{ref}(t)'
},"location", 'northeast');
title('TITLE')
l1 = legend;
set(l1,'FontName','Times')
subplot(2,1,2);
h2 = plot(x,y2);
set(h2,'LineWidth',4)
set(gca,'FontSize',32)
set(gca,'FontName','Times')
set(get(gca,'Ylabel'),'String','TTEST test \rho \rightarrow','FontWeight','Bold','FontSize',32)
set(get(gca,'Xlabel'),'String','agc / -\rightarrow','FontWeight','Bold','FontSize',32)
legend({
'h_{ref}(t)'
},"location", 'northeast');
l2 = legend;
set(l2,'FontName','Times')
print ('title_axis.pdf', '-dpdfcairo', '-S1000,600');

Barplot with errors in bokeh

I am trying to draw a figure like that http://seaborn.pydata.org/_images/seaborn-barplot-1.png
As I understand bokeh don't have special method for barplot with error, so I decided to use Seaborn and then convert it into bokeh chart by to_bokeh() function.
sns.set_style("whitegrid")
plot = sns.barplot(data=[[1,2], [3,4]])
plot.get_figure().savefig('1.jpg')
l = layout([[widgetbox(*controls), to_bokeh(plot.get_figure())]])
save(l)
It save normal plot, like at the picture, but bokeh shows only error line, and no bars.
What do I wrong, is it bug? Is there simpler way to draw chars like that in bokeh. I also should use strings as a ticks.Does bokeh support it?
I have found solution (at least I hope :) )
box_plot = figure(x_range=['Ctrl', '- FBC', 'Rescue'])
X = range(1, 4)
Y = some_data # e.g. mean(data)
Err = another_piece_of_data # e.g. std(data)
box_plot.vbar(x=X, width=0.5, top=Y)
#add errors
err_xs = []
err_ys = []
for x, y, err in zip(X, Y, Err):
err_xs.append((x, x))
err_ys.append((y - err, y + err))
box_plot.multi_line(err_xs, err_ys, color='red', line_width=2)
l = layout([[box_plot]])
save(l)

Connecting arcs between lines in Dot (GraphViz)

I've got to do up a state space graph for my AI course, and I was hoping to use GraphViz to make it (so much faster than Dia). The one thing I can't seem to figure out how to do is how to do an "And" connection, which is basically an arc between two lines connecting to the same node. Is this possible?
Yes. While there's no explicit dot syntax for this, here's the way it's nearly always done:
# just graph set-up
digraph new_graph {
ratio = "auto"
mincross = 2.0
# draw some nodes
"001" [shape=box, regular=1, style=filled, fillcolor="#FCD975"] ;
"017" [shape=circle , regular=1,style=filled,fillcolor="#9ACEEB" ] ;
"007" [shape=diamond , regular=1,style=filled,fillcolor="#FCD975" ] ;
# the key line--creating tiny node w/ no label, no color
# i use this style because it mimics the 'midpoint' style used in Omnigraffle et al.
"LN01" [shape=diamond,style=filled,label="",height=.1,width=.1] ;
# draw the edges
"001" -> "LN01" [dir=none,weight=1] ;
"007" -> "LN01" [dir=none,weight=1] ;
"LN01" -> "017" [dir=none, weight=2] ;
}
alt text http://img121.imageshack.us/img121/2547/dotgvziv.png

Resources