How to create TradingView indicators that look like this? - math

I've been trying to create similar indicator to this
This is the reference
I have the code for RSI, Stochastic RSI, MACD and 50/100/200 MA (with crosses), but I couldn't find any information on how to create the visuals like in the reference altough I was studying for quite a long time
Here is the code for these indicators:
50/100/200 MA with crosses (coded by myself)
indicator(title="3 EMA with Cross", shorttitle="3EMA Cross", overlay=true)
fast = 50
mid = 100
slow = 200
fastEMA = ta.ema(close, fast)
midEMA = ta.ema(close, mid)
slowEMA = ta.ema(close, slow)
bullishCross = ta.crossover(fastEMA, slowEMA)
bearishCross = ta.crossunder(fastEMA, slowEMA)
if (bullishCross)
lbl = label.new(bar_index, low, "Golden Cross")
label.set_color(lbl, color.green)
label.set_yloc(lbl, yloc.belowbar)
label.set_style(lbl, label.style_label_up)
if (bearishCross)
lbl = label.new(bar_index, low, "Death Cross")
label.set_color(lbl, color.red)
label.set_yloc(lbl, yloc.abovebar)
label.set_style(lbl, label.style_label_down)
plot(fastEMA, color=color.green, linewidth=2)
plot(midEMA, color=color.yellow, linewidth=2)
plot(slowEMA, color=color.red, linewidth=2)
RSI
indicator(title="Relative Strength Index", shorttitle="RSI", format=format.price, precision=2,
timeframe="", timeframe_gaps=true)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings")
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA = ma(rsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"
plot(rsi, "RSI", color=#7E57C2)
plot(rsiMA, "RSI-based MA", color=color.yellow)
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green)
bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill")
MACD
indicator(title="Moving Average Convergence Divergence", shorttitle="MACD", timeframe="",
timeframe_gaps=true)
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Line  ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line  ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above   Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ?
col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(macd, title="MACD", color=col_macd)
plot(signal, title="Signal", color=col_signal)
Stochastic RSI
smoothK = input.int(3, "K", minval=1)
smoothD = input.int(3, "D", minval=1)
lengthRSI = input.int(14, "RSI Length", minval=1)
lengthStoch = input.int(14, "Stochastic Length", minval=1)
src = input(close, title="RSI Source")
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
plot(k, "K", color=#2962FF)
plot(d, "D", color=#FF6D00)
h0 = hline(80, "Upper Band", color=#787B86)
h1 = hline(20, "Lower Band", color=#787B86)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")```
//MACD
indicator(title="Moving Average Convergence Divergence", shorttitle="MACD", timeframe="", timeframe_gaps=true)
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Line  ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line  ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above   Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(macd, title="MACD", color=col_macd)
plot(signal, title="Signal", color=col_signal)

You can use labels with offset for that. Offset will help you with the placement.
Update the labels with each bar and delete the old bars.
A simple example:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius
//#version=5
indicator("My script")
rsi = ta.rsi(close, 14)
ema50 = ta.ema(close, 50)
rsi_off = 50
ema50_off = 25
rsi_up_trend = rsi < 30
ema_up_trend = close > ema50
var label l_rsi = na
var label l_ema50 = na
if barstate.islast
l_rsi := label.new(bar_index - rsi_off, 1, "RSI", color=rsi_up_trend ? color.green : color.red, style=label.style_triangleup, textcolor=color.white)
l_ema50 := label.new(bar_index - ema50_off, 1, "EMA50", color=ema_up_trend ? color.green : color.red, style=label.style_triangleup, textcolor=color.white)
label.delete(l_rsi[1])
label.delete(l_ema50[1])

Related

incorrect fill when plot is in stepline slyle

//#version=5
indicator(title="Weeks_OC", shorttitle="Weeks_OC", overlay=true)
w_close = request.security(syminfo.tickerid, "W", close, barmerge.gaps_off, barmerge.lookahead_on)
w_open = request.security(syminfo.tickerid, "W", open,barmerge.gaps_off, barmerge.lookahead_on)
p1=plot(w_open,title='w_open', color = w_close >= w_open ? color.blue : color.red, style=plot.style_stepline, linewidth=3)
p2=plot(w_close,title='w_close',color = w_close >= w_open ? color.blue : color.red, style=plot.style_stepline, linewidth=3)
fill(plot1=p1, plot2=p2, color = w_close >= w_open ? color.blue : color.red)
PineScript v5
Simple indicator that shows open-close area of a week.
Fill function seems works incorrectly when given plot is in stepline slyle
I think you have Extended hours enabled. Please switch it to Regular Trading Hours.
I think this is what you're looking for:
//#version=5
indicator(title="Weeks_OC", shorttitle="Weeks_OC", overlay=true)
var int transp = input.int(50, 'Transparency', 0, 100)
var color c_blue = color.new(color.blue, transp)
var color c_red = color.new(color.red, transp)
[w_open,w_close] = request.security(syminfo.tickerid, 'W', [open,close], barmerge.gaps_off, barmerge.lookahead_on)
newWeek = ta.change(weekofyear)
mycolor = newWeek ? na : w_close >= w_open ? c_blue : c_red
p1 = plot(w_open, 'w_open', mycolor)
p2 = plot(w_close, 'w_close', mycolor)
fill(p1, p2, mycolor)
Which yields

Plotted arrows aren't displayed below or above bar graph in Pine

I have the next code.
//#version=4
study(title="MACD", shorttitle="MACD")
// Getting inputs
fast_length = input(title="Fast Length", type=input.integer, defval=11)
slow_length = input(title="Slow Length", type=input.integer, defval=22)
src = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = #0094ff
col_signal = #ff6a00
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 )
plot(macd, title="MACD", color=col_macd, transp=0)
plot(signal, title="Signal", color=col_signal, transp=0)
currMacd = hist[0]
prevMacd = hist[1]
buy = currMacd > 0 and prevMacd <= 0
sell = currMacd < 0 and prevMacd >= 0
timetobuy = buy==1
timetosell = sell==1
tup = barssince(timetobuy[1])
tdn = barssince(timetosell[1])
long = tup>tdn?1:na
short = tdn>tup?1:na
plotshape(long==1?buy:na, color=#26A69A, location=location.abovebar, style=shape.arrowup, title="Buy Arrow", transp=0)
plotshape(short==1?sell:na, color=#EF5350, location=location.belowbar, style=shape.arrowdown, title="Sell Arrow", transp=0)
As you can see, it is the macd histogram code with some plot code to graph arrows near the histogram. I configured their location as above and below. However, they are displayed far from the graph.
How can I plot the arrows above and below the macdh bars?
By using location=location.abovebar the function is putting the level of the symbol's price in play, which ruins your indicator's scale. The solution is to use location=location.top instead:
plotshape(long==1?buy:na, color=#26A69A, location=location.top, style=shape.arrowup, title="Buy Arrow", transp=0)
plotshape(short==1?sell:na, color=#EF5350, location=location.bottom, style=shape.arrowdown, title="Sell Arrow", transp=0)

How can I avoid pie chart&legend overlap in R?

I wanna create a pie chart of crime types,and add a legend on the right hand,but I tried many times to avoid overlapping,doesn't work at all.
table(dd$Primary.Type.new)
ARSON ASSAULT BATTERY BURGLARY
833 30743 91237 29298
CRIMINAL DAMAGE CRIMINAL TRESPASS DECEPTIVE PRACTICE HOMICIDE
57539 14353 17472 640
KIDNAPPING MOTOR VEHICLE THEFT NARCOTOCS OFFENSE INVOLVING CHILDREN
517 23724 55685 3347
OTHER OFFENSE PUBLIC OFFENSE PUBLIC PEACE VIOLATION ROBBERY
30878 3833 3632 18891
SEX_CRIME THEFT WEAPONS VIOLATION
9331 103255 4792
Type <- table(dd$Primary.Type.new)
Here's that from dput():
structure(c(ARSON = 833L, ASSAULT = 30743L, BATTERY = 91237L,
BURGLARY = 29298L, `CRIMINAL DAMAGE` = 57539L, `CRIMINAL TRESPASS` = 14353L,
`DECEPTIVE PRACTICE` = 17472L, HOMICIDE = 640L, KIDNAPPING = 517L,
`MOTOR VEHICLE THEFT` = 23724L, NARCOTOCS = 55685L, `OFFENSE INVOLVING CHILDREN` = 3347L,
`OTHER OFFENSE` = 30878L, `PUBLIC OFFENSE` = 3833L, `PUBLIC PEACE VIOLATION` = 3632L,
ROBBERY = 18891L, `SEX CRIME` = 9331L, THEFT = 103255L, `WEAPONS VIOLATION` = 4792L
), .Dim = 19L, .Dimnames = list(. = c("ARSON", "ASSAULT", "BATTERY",
"BURGLARY", "CRIMINAL DAMAGE", "CRIMINAL TRESPASS", "DECEPTIVE PRACTICE",
"HOMICIDE", "KIDNAPPING", "MOTOR VEHICLE THEFT", "NARCOTOCS",
"OFFENSE INVOLVING CHILDREN", "OTHER OFFENSE", "PUBLIC OFFENSE",
"PUBLIC PEACE VIOLATION", "ROBBERY", "SEX CRIME", "THEFT", "WEAPONS VIOLATION"
)), class = "table") -> Type
piepercent<- round(100*Type/sum(Type), 1)
pie(Type, edges = 200, radius = 0.8,
clockwise = FALSE,angle = 45, col = rainbow(length(Type)), main = "Pie Chart of Primary Crime Types", labels = piepercent,labelcex = 0.8)
legend("right", inset = .05, title = "Primary Crime Type",legend= dd$Primary.Type.new,fill = rainbow(length(Type)), horiz=FALSE,cex = 0.6)
I tried to use par(), but doestn't work.
and BTW how can I change the labels into percentage? such as convert 20.7 into 20.7%.
Thank you very much.
Update
I also tried 3D piechart
library(plotrix)
pie3D(Type,labels = piepercent,explode = 0.1, main = "3D Pie Chart of
Primary Crime Types", labelcex = 0.8)
legend("bottom", inset = .05, title = "Primary Crime Type",legend= dd$Primary.Type.new,fill = rainbow(length(Type)), horiz=TRUE,cex = 0.6)
I hesitate to post this since this is an absolutely terrible use case for a pie chart, but it's possible to make it a bit more readable and color-blind friendly:
structure(c(ARSON = 833L, ASSAULT = 30743L, BATTERY = 91237L,
BURGLARY = 29298L, `CRIMINAL DAMAGE` = 57539L, `CRIMINAL TRESPASS` = 14353L,
`DECEPTIVE PRACTICE` = 17472L, HOMICIDE = 640L, KIDNAPPING = 517L,
`MOTOR VEHICLE THEFT` = 23724L, NARCOTOCS = 55685L, `OFFENSE INVOLVING CHILDREN` = 3347L,
`OTHER OFFENSE` = 30878L, `PUBLIC OFFENSE` = 3833L, `PUBLIC PEACE VIOLATION` = 3632L,
ROBBERY = 18891L, `SEX CRIME` = 9331L, THEFT = 103255L, `WEAPONS VIOLATION` = 4792L
), .Dim = 19L, .Dimnames = list(. = c("ARSON", "ASSAULT", "BATTERY",
"BURGLARY", "CRIMINAL DAMAGE", "CRIMINAL TRESPASS", "DECEPTIVE PRACTICE",
"HOMICIDE", "KIDNAPPING", "MOTOR VEHICLE THEFT", "NARCOTOCS",
"OFFENSE INVOLVING CHILDREN", "OTHER OFFENSE", "PUBLIC OFFENSE",
"PUBLIC PEACE VIOLATION", "ROBBERY", "SEX CRIME", "THEFT", "WEAPONS VIOLATION"
)), class = "table") -> Type
Order the slices (IMPORTANT):
Type <- sort(Type, decreasing = TRUE)
Proper % and decent labels:
piepercent <- scales::percent(as.numeric(Type/sum(Type)))
Margins:
par(mar = c(1, 1, 1, 1)) # bltr
pie(
Type,
edges = 200,
radius = 0.8,
clockwise = TRUE, # IMPORTANT
angle = 45,
col = viridis::viridis_pal(option = "magma", direction=-1)(length(Type)), # BETTER COLOR PALETTE
labels = tail(piepercent, -7), # NEVER DISPLAY OVERLAPPING LABELS
cex = 0.7
)
legend(
x = 1.2, # DELIBERATE POSITION
y = 0.5, # DELIBERATE POSITION
inset = .05,
title = "Primary Crime Type",
legend = names(Type), # YOU WERE PASSING IN _ALL_ THE REPEAT NAMES
fill = viridis::viridis_pal(option = "magma", direction=-1)(length(Type)), # USE THE SAME COLOR PALETTE
horiz = FALSE,
cex = 0.6, # PROPER PARAMETER FOR TEXT SIZE
text.width = 0.7 # SET THE BOX WIDTH
)
Add the title manually:
title("Pie Chart of Primary Crime Types", line = -1)
Can't let a pie chart stand alone (and, now, a 3D one at that):
structure(list(cat = c("Arson", "Assault", "Battery", "Burglary",
"Criminal Damage", "Criminal Trespass", "Deceptive Practice",
"Homicide", "Kidnapping", "Motor Vehicle Theft", "Narcotocs",
"Offense Involving Children", "Other Offense", "Public Offense",
"Public Peace Violation", "Robbery", "Sex Crime", "Theft", "Weapons Violation"
), val = c(833, 30743, 91237, 29298, 57539, 14353, 17472, 640,
517, 23724, 55685, 3347, 30878, 3833, 3632, 18891, 9331, 103255,
4792), pct = c(0.001666, 0.061486, 0.182474, 0.058596, 0.115078,
0.028706, 0.034944, 0.00128, 0.001034, 0.047448, 0.11137, 0.006694,
0.061756, 0.007666, 0.007264, 0.037782, 0.018662, 0.20651, 0.009584
)), class = "data.frame", row.names = c(NA, -19L)) -> xdf
dplyr::arrange(xdf, pct) %>%
dplyr::mutate(cat = factor(cat, levels=cat)) %>%
dplyr::mutate(lab = sprintf("%s (%s)", scales::comma(val), scales::percent(pct))) %>%
ggplot(aes(pct, cat)) +
geom_segment(aes(xend=0, yend=cat), size=4, color = "#617a89") +
geom_label(
aes(label=lab), label.size = 0, hjust=0, nudge_x=0.001,
size = 3, family = hrbrthemes::font_rc, color = "#909495"
) +
hrbrthemes::scale_x_percent(expand=c(0,0.001), limits=c(0,0.25)) +
labs(x = NULL, y = NULL, title = "'Theft', 'Battery' & 'Criminal Damage' Account\nfor Half of Primary Recorded Crime Types") +
hrbrthemes::theme_ipsum_rc(grid="X") +
theme(axis.text.x = element_blank())
How I got xdf:
readLines(textConnection("ARSON ASSAULT BATTERY BURGLARY
833 30743 91237 29298
CRIMINAL_DAMAGE CRIMINAL_TRESPASS DECEPTIVE_PRACTICE HOMICIDE
57539 14353 17472 640
KIDNAPPING MOTOR_VEHICLE_THEFT NARCOTOCS OFFENSE_INVOLVING_CHILDREN
517 23724 55685 3347
OTHER_OFFENSE PUBLIC_OFFENSE PUBLIC_PEACE_VIOLATION ROBBERY
30878 3833 3632 18891
SEX_CRIME THEFT WEAPONS_VIOLATION
9331 103255 4792")) %>%
trimws() %>%
stri_split_regex("[[:space:]]+") -> x
do.call(rbind.data.frame, lapply(seq.int(1, length(x), 2), function(i) {
data.frame(
cat = stri_trans_totitle(gsub("_", " ", x[[i]])),
val = as.numeric(x[[i+1]]),
stringsAsFactors = FALSE
)
})) %>%
mutate(pct = val/sum(val)) -> xdf

How to put a text legend on a ggplot graph of data?

I have some data:
donnees <- structure(list(mean.time = c(66.2181493259296, 38.4214009587611,28.3780846407761, 23.6036479741174, 21.1194982724492, 18.2304201307749, 17.255935716945, 15.1999929855212, 14.4373235262462), interval.time = c(2.02676652919753, 1.11352244913202, 0.852970451889973, 0.659463003712615, 0.637078718678222, 0.555560539640353, 0.523901049738113, 0.459577876757762, 0.42846867586966), mean.speed = c(93.3820017657387, 161.279607915939, 218.506927701215,257.296969741989, 295.210612887155, 344.350019217133, 364.011355824999, 409.234700329235, 437.398681209406), interval.speed = c(2.88657084170069, 5.02519369247631, 6.79320499564379, 7.66765106354858, 9.45539113245263, 10.9383151684182, 12.2017419883015, 13.715012760365, 16.6173823082674), mean.dist = c(5059.20542230044, 5025.32849954932, 4979.53881596498, 4994.56758567708, 4980.47651740827, 4991.06590346422, 4984.66564161804, 4932.67139724921, 4991.32367321949), interval.distance = c(44.8556012621449, 41.8511306706474, 42.6986600944198, 43.1898193770464, 42.7477524465553, 43.4197913676737, 42.9860392430236, 41.6610917291015, 42.4239685871405), lambda = 1:9), .Names = c("mean.time", "interval.time", "mean.speed", "interval.speed", "mean.dist", "interval.distance", "lambda"), row.names = c(NA, 9L), class = "data.frame")
I use the following function to get the confident interval for a given lambda:
int.ech = function(vector,conf.level=0.95,na.rm=T){
if (length(vector)==0) { cat("Erreur ! Le vecteur ",substitute(vector),"est vide.\n")}
else { s = var(vector,na.rm=na.rm)
n = length(vector)-sum(is.na(vector))
ddl = n - 1 ; proba = (1-conf.level)*100 ; proba = (100-proba/2)/100
t_student = qt(proba, ddl) # quantile
intervalle = t_student * sqrt(s/n)
moyenne = mean(vector,na.rm=na.rm) ; return(intervalle) }
}
Then, I plot the data with ggplot :
ggplot(donnees, aes(x = lambda, y = donnees$mean.speed))+
geom_point() + geom_path(color = "blue") +
geom_errorbar(aes(ymin = donnees$mean.speed - donnees$interval.speed, ymax = donnees$mean.speed + donnees$interval.speed)) +
labs(title = 'Distibution of the infection speed (m/min) once the malware have reached the edge in function of lambda (users/km)', x = "lambda : users density (users/km)", y = "Infection speed (m/min)") +
labs(linetype='custom title')
I have a text which I want to put on legend of this graph :
texte <- c(paste("window =",win,"km",sep= " "),paste("r_infection =", radius*1000,"m",sep=" "),paste("gamma =",gamma,"km/km^2",sep=" "))
The problem is when I want to execute the legend function :
legend("topleft", legend = texte)
I have this error :
Error in strwidth(legend, units = "user", cex = cex, font = text.font) : plot.new has not been called yet
For information, I get the same answer when I just execute :
ggplot(donnees, aes(x = lambda, y = meanspeed)) + legend("topleft", legend = texte)
Thank you for your help.

R:Time dependent parameters in a differential equations model

I have a differential equations model (see below), I am looking for some way to change some of the values of the parameters at a certain time step or at a certain value of one of the state variables (or another way if it works better). For example, I would like to change GammaQR and GammaQD from 0 to .02 at time step 5 (or possibly, if it works better, when H > .04). I have no clue how to go about this and would really appreciate any advice! Thanks!
VS = 0.01
VE = 0.01
VH = 0.01
BSE = 10 #
BSI = 10 #
THE = 1/10
TEI = 1/3
DeltaID = .5
GammaIR = .5
XIQ = 0.001
XEQ = 0.01
XHQ = 0.05
GammaQR = .02
GammaQD = .02
library(deSolve)
pars <- c(VS, VE, VH, BSE, BSI, THE, TEI, DeltaID, GammaIR, XIQ, XEQ, XHQ, GammaQR)
init.values <- c(S = .99 , H = .01 , E = 0 , V = 0, I = 0 , Q = 0 , D = 0 , R = 0 )
times <- seq(0, 60, by = 1)
Smallpox <- function(time, y.values, parameters){
with(as.list(c(y.values, parameters)), {
dS.dt = -VS*S - BSI*S*I - BSE*E*S
dH.dt = BSI*S*I + BSE*E*S - THE*H - XHQ*H - VH*H
dE.dt = THE*H - XEQ*E - VE*E - DeltaID*E - TEI*E
dV.dt = VS*S + VE*E + VH*H
dI.dt = TEI*E - XIQ*I - GammaIR*I - DeltaID*I
dQ.dt = XHQ*H + XIQ*I + XEQ*E - GammaQR*Q - GammaQD*Q
dD.dt = DeltaID*I + DeltaID*E + GammaQD*Q
dR.dt = GammaQR*Q + DeltaID*I
return(list(c(dS.dt, dH.dt, dE.dt, dV.dt, dI.dt, dQ.dt, dD.dt, dR.dt)))
})
}
out <- as.data.frame(ode(func = Smallpox, y = init.values, parms = pars, times = times))
tail(out)
matplot(out$time, out[ ,2:9], type = "l", xlab = "time", ylab = "percent of population", main = "Model Name", lwd = 2, col = c("black", "red", "green", "Blue", "cyan", "purple", "grey", "magenta"), lty = 1:8)

Resources