How to change the color for many curves in the same figure in Scilab? - scilab

I am solving the SIRD model by using Scilab, I am simulating this model for r and b vectors since I put b as a constant value and simulating for r vector by using for loop and I am plotting four outputs (S, I, R, and D) by using subplot command, but I get the four curves in the same colour. How can I use different colours in the same figure? I used plot2d(t, x(1,:),style=[color("red"),color("green"),,color("blue")]) but it does not work. I am going to attach my code and the output figures.
Thanks in advance.
Figures
clear
function dxdt=f(t,x)
S=x(1);
I=x(2);
R=x(3);
D=x(4);
dxdt=[-alpha*b*S*I
alpha*b*S*I-(I/r)
((1-m)*I)/r
(m*I)/r]
endfunction
N=10^7;
alpha=10^-6;
m=0.6;
b_vec=[0.05 0.025 0.01];
r_vec=[10 5 3];
t=linspace(0,150,1000);
x0=[10^7-1000;1000;0;0];
// simulation for constant beta b=0.05
clf(0); scf(0);
for i=1:3
b=0.05;
r=r_vec(i)
x=ode(x0,0,t,f)
subplot(2,2,1)
plot(t,x(1,:))
set(gca(),"auto_clear","off") //hold on
xlabel('time[days]')
ylabel('S')
title ('b=0.05')
legend ('r=10','r=5','r=3')
subplot(2,2,2)
plot(t,x(2,:))
set(gca(),"auto_clear","off") //hold on
xlabel('time[days]')
ylabel('I')
title ('b=0.05')
legend ('r=10','r=5','r=3')
subplot(2,2,3)
plot(t,x(3,:))
set(gca(),"auto_clear","off") //hold on
xlabel('time[days]')
ylabel('R')
title ('b=0.05')
legend ('r=10','r=5','r=3')
subplot(2,2,4)
plot(t,x(4,:))
set(gca(),"auto_clear","off") //hold on
xlabel('time[days]')
ylabel('D')
title ('b=0.05')
legend ('r=10','r=5','r=3')
end

Just add
colors = ["r" "g" "b"];
just before the for loop, and
plot(t,x(#,:), colors(i))
for every plot() command, and that's it.
By the way, all "hold on" rows are useless, since this mode is the default one. And correctly indenting your code makes it always better readable.

Related

Creating animated plots in the command line with Julia

Julia has the delightful ability to generate plots constructed from Unicode symbols which are printed directly to the command line in a very straightforward way. For example, the following code generates a Unicode plot of a sine function directly to the command line:
using Plots
unicodeplots();
x = [0:0.1:2*pi;];
y = sin.(x);
plot(x,y)
I would like to try to find a way to create an animated plot of this form directly on the command line. Ideally, I would like to generate a single plot in Unicode that is ``updated" in such a way that it appears animated.
However, although printing hundreds of distinct frames to the command line is naturally less appealing, such a solution is acceptable if it ``looks" like an animation. Another less acceptable solution is to print such Unicode plots into a gif in a way that is consistent for all platforms; attempts to do any of this involving jury-rigging #animate and #gif have largely failed, since either function cannot even print Unicode plots to a file in the Windows form of Julia.
UPDATE: Here is an example of code that generates an "animation" in the command line that is not really acceptable, which simply plots each distinct frame followed by "spacing" in the command line provided by a special Unicode character (tip provided by niczky12):
using Plots
unicodeplots();
n = 100;
x = [0:0.1:4*pi;];
for i = 1:30
y = sin.(x .+ (i/2));
plot(x, y, show=true, xlims = (0,4*pi), ylims = (-1,1))
sleep(0.01)
println("\33[2J")
end
A slight improvement might be this:
let
print("\33[2J")
for i in 1:30
println("\33[H")
y = sin.(x .+ (i/2));
plot(x, y, show=true, xlims = (0,4*pi), ylims = (-1,1))
sleep(0.01)
end
end

xticks' labels formatting in Julia Plots

Assume my Julia code is
using Plots
t = -π:1e-4:π
y = sin.(t)
plot(t,y,lw=3,legend=false)
plot!(xticks=([-π/2],["(-\\pi)/2"]))
where I want to show the parenthesis in the numerator of xticks' label while keeping its "rational" form, i.e., I don't want the numerator and the denominator to be inline. The output of the above code looks like this
One may see that the xticks' label does not include the desired parenthesis.
Here is another code to show the above function:
using Plots
t = -π:1e-4:π
y = sin.(t)
plot(t,y,lw=3,color=2,legend=false)
plot!(xticks=([-π/2],["(-π)/2"]))
which as it can be seen, the only difference with the former is in the xticks' label (in the former it is \\pi while in the latter it is π).
Now the picture looks like this:
which does not show the label in the "rational" form, i.e., both numerator and the denominator are inline which is undesired. Is there any way to overcome this issue?
Try using LaTeXStrings:
using Plots
using LaTeXStrings
gr()
t = -π:1e-4:π
y = sin.(t)
plot(t,y,lw=3,legend=false)
plot!(xticks=([-π/2],[L"\frac{(-\pi)}{2}"]))

Multiple histograms in Julia using Plots.jl

I am working with a large number of observations and to really get to know it I want to do histograms using Plots.jl
My question is how I can do multiple histograms in one plot as this would be really handy. I have tried multiple things already, but I am a bit confused with the different plotting sources in julia (plots.jl, pyplot, gadfly,...).
I don't know if it would help for me to post some of my code, as this is a more general question. But I am happy to post it, if needed.
There is an example that does just this:
using Plots
pyplot()
n = 100
x1, x2 = rand(n), 3rand(n)
# see issue #186... this is the standard histogram call
# our goal is to use the same edges for both series
histogram(Any[x1, x2], line=(3,0.2,:green), fillcolor=[:red :black], fillalpha=0.2)
I looked for "histograms" in the Plots.jl repo, found this related issue and followed the links to the example.
With Plots, there are two possibilities to show multiple series in one plot:
First, you can use a matrix, where each column constitutes a separate series:
a, b, c = randn(100), randn(100), randn(100)
histogram([a b c])
Here, hcat is used to concatenate the vectors (note the spaces instead of commas).
This is equivalent to
histogram(randn(100,3))
You can apply options to the individual series using a row matrix:
histogram([a b c], label = ["a" "b" "c"])
(Again, note the spaces instead of commas)
Second, you can use plot! and its variants to update a previous plot:
histogram(a) # creates a new plot
histogram!(b) # updates the previous plot
histogram!(c) # updates the previous plot
Alternatively, you can specify which plot to update:
p = histogram(a) # creates a new plot p
histogram(b) # creates an independent new plot
histogram!(p, c) # updates plot p
This is useful if you have several subplots.
Edit:
Following Felipe Lema's links, you can implement a recipe for histograms that share the edges:
using StatsBase
using PlotRecipes
function calcbins(a, bins::Integer)
lo, hi = extrema(a)
StatsBase.histrange(lo, hi, bins) # nice edges
end
calcbins(a, bins::AbstractVector) = bins
#userplot GroupHist
#recipe function f(h::GroupHist; bins = 30)
args = h.args
length(args) == 1 || error("GroupHist should be given one argument")
bins = calcbins(args[1], bins)
seriestype := :bar
bins, mapslices(col -> fit(Histogram, col, bins).weights, args[1], 1)
end
grouphist(randn(100,3))
Edit 2:
Because it is faster, I changed the recipe to use StatsBase.fit for creating the histogram.

How to have title in R Vennerable Venn Diagram?

I cannot find anything in documentation here.
Code
library("Vennerable")
data(StemCell)
Vstem <- Venn(StemCell)
Vstem3 <- Vstem[, c("OCT4", "SOX2", "NANOG")]
tl <- "masi"
plot(Vstem3, doWeights = TRUE, type = "circles")
Tried unsuccessfully
plot(..., main = tl)
plot(..., title = tl)
plot(...); title(tl)
plt <- plot(...); title(plt, tl)
Fig. 1 Wrong output without title
R: 3.3.1
OS: Debian 8.5
user20650 answer in comments summarised here. Try (1-2) and choose what fits best.
The plot method is based on the grid package so the normal base R plot approaches to add a title won't work. Looking at the arguments of args(Vennerable:::plotVenn), there doesn't seem a way to add a title and unhelpfully the plots do not return a grid object. So you can just draw a title on the plot window with the following
grid.text("masi", y=0.9, gp=gpar(col="red", cex=2))
As an alternative method, you could grab the grob and then use grid.arrange to plot the title
gridExtra::grid.arrange(grid::grid.grabExpr(plot(Vstem3, doWeights = TRUE,
type = "circles")), top="masi")
The grid.arrange way adds the title as a separate grob, and then they are arranged in two rows. So when resizing the graphics window, it still appears above the plot. This won't be true when drawing straight on the window (as in the first version).
Note: you do not need to use gridExtra, you could do this in grid.
Fig. 1 Output from (1),
Fig. 2 Output from (2)
I think (1) could be better with more adjustments, but now (2) is better.

R, graph of binomial distribution

I have to write own function to draw the density function of binomial distribution and hence draw
appropriate graph when n = 20 and p = 0.1,0.2,...,0.9. Also i need to comments on the graphs.
I tried this ;
graph <- function(n,p){
x <- dbinom(0:n,size=n,prob=p)
return(barplot(x,names.arg=0:n))
}
graph(20,0.1)
graph(20,0.2)
graph(20,0.3)
graph(20,0.4)
graph(20,0.5)
graph(20,0.6)
graph(20,0.7)
graph(20,0.8)
graph(20,0.9)
#OR
graph(20,scan())
My first question : is there any way so that i don't need to write down the line graph(20,p) several times except using scan()?
My second question :
I want to see the graph in one device or want to hit ENTER to see the next graph. I wrote
par(mfcol=c(2,5))
graph(20,0.1)
graph(20,0.2)
graph(20,0.3)
graph(20,0.4)
graph(20,0.5)
graph(20,0.6)
graph(20,0.7)
graph(20,0.8)
graph(20,0.9)
but the graph is too tiny. How can i present the graphs nicely with giving head line n=20 and p=the value which i used to draw the graph?[though it can be done by writing mtext() after calling the function graphbut doing so i have to write a similar line few times. So i want to do this including in function graph. ]
My last question :
About comment. The graphs are showing that as the probability of success ,p is increasing the graph is tending to right, that is , the graph is right skewed.
Is there any way to comment on the graph using program?
Here a job of mapply since you loop over 2 variables.
graph <- function(n,p){
x <- dbinom(0:n,size=n,prob=p)
barplot(x,names.arg=0:n,
main=sprintf(paste('bin. dist. ',n,p,sep=':')))
}
par(mfcol=c(2,5))
mapply(graph,20,seq(0.1,1,0.1))
Plotting base graphics is one of the times you often want to use a for loop. The reason is because most of the plotting functions return an object invisibly, but you're not interested in these; all you want is the side-effect of plotting. A loop ignores the returned obects, whereas the *apply family will waste effort collecting and returning them.
par(mfrow=c(2, 5))
for(p in seq(0.1, 1, len=10))
{
x <- dbinom(0:20, size=20, p=p)
barplot(x, names.arg=0:20, space=0)
}

Resources