dropTA specific indicator by name - r

Can't figure out how to delete a specified indicator by name from TA list in R quantmod.
require("quantmod")
getSymbols("AAPL", src="yahoo", from = '2018-01-1', to = '2019-01-1')
#my custom indicator
AAPL_sma_50 <- SMA(
Cl(AAPL),
n = 50
)
candleChart(AAPL, up.col = "black", dn.col = "red", theme = "white")
addTA(AAPL_sma_50, on = 1, col = "blue")
addBBands()
listTA()
listTA() output:
[[1]] addVo()
[[2]] addTA(ta = AAPL_sma_50, on = 1, col = "blue")
[[3]] addBBands()
I'm able to do delete built-in with dropTA('addBBands'), but cannot delete custom indicator the same way:
dropTA('AAPL_sma_50')
Error in dropTA("AAPL_sma_50") : nothing to remove
dropTA(2) is not working by index either - it always deletes first element
How I can delete the second custom one only, or how to create it, to be able to delete later by name- e.g. dropTA('myCustomIndicator')

There are a few options to remove TA's from the plot. The trick is to know that when you use addTA(my_indicator), you can not use dropTA(my_indicator). Because you added the TA via addTA(), so you need to call dropTA(ta = "addTA").
Now a few possibilies:
dropTA(all = TRUE) # removes all technical indicators
dropTA(ta = "addBBAnds") # removes the bolinger bands you added via addBBands()
If you added a few custom TA's with addTA, you can specify which version to delete if you now the order.
dropTA(ta = "addTA", occ = 2) # removes the second occurence of the TA you added
dropTA(ta = "addTA", all = TRUE) # removes all TA's added with addTA
This is useful when you have used multiple addEMA or addSMA indicators to the chart.
example with EMA indicators:
library(quantmod)
getSymbols("AAPL", src="yahoo", from = '2018-01-1', to = '2019-01-1')
candleChart(AAPL, up.col = "black", dn.col = "red", theme = "white")
addEMA(Cl(AAPL), n = 13, on = 1)
addEMA(Cl(AAPL), n = 21, on = 1)
addEMA(Cl(AAPL), n = 5, on = 1)
dropTA(ta = "addEMA", occ = 2) # removes the second occurence of the EMA's you added
dropTA(ta = "addEMA", all = TRUE) # removes all (other) EMA's added

Related

Create an R function that normalizes data based on input values

I don't make to many complicated functions and typically stick with very basic ones. I have a question, how do I create a function that takes a dataset and normalizes based on desired normalization method and boxplots the output? Currently norm_method is different between the norm methods, was wondering if there is a way to call this in the start of function to pull through the correct method? Below is the code I created, but am stuck how to proceed.
library(reshape2) # for melt
library(cowplot)
demoData;
# target_deoData will need to be changed at some point
TestFunc <- function(demoData) {
# Q3 norm (75th percentile)
target_demoData <- normalize(demoData ,
norm_method = "quant",
desiredQuantile = .75,
toElt = "q_norm")
# Background normalization without spike
target_demoData <- normalize(demoData ,
norm_method = "neg",
fromElt = "exprs",
toElt = "neg_norm")
boxplot(assayDataElement(demoData[,1:10], elt = "q_norm"),
col = "red", main = "Q3",
log = "y", names = 1:10, xlab = "Segment",
ylab = "Counts, Q3 Normalized")
boxplot(assayDataElement(demoData[,1:10], elt = "neg_norm"),
col = "blue", main = "Neg",
log = "y", names = 1:10, xlab = "Segment",
ylab = "Counts, Neg. Normalized")
}
You might want to consider designing your normalize() and assayDataElement() functions to take ..., which provides more flexibility.
In lieu of that, given the examples above, you could make a simple configuration list, and elements of that configuration are passed to your normalize() and assayDataElement() functions, like this:
TestFunc <- function(demoData, method=c("quant", "neg")) {
method = match.arg(method)
method_config = list(
"quant" = list("norm_args" = list("norm_method" = "quant", desired_quantile = 0.75, "toElt" = "q_norm"),
"plot_args" = list("col"="red", main="Q3", ylab = "Counts, Q3 Normalized")),
"neg" = list("norm_args" = list("fromElt" = "exprs", "toElt" = "neg_norm"),
"plot_args" = list("col"="blue", main="Neg", ylab = "Counts, Neg Normalized"))
)
mcn = method_config[[method]][["norm_args"]]
mcp = method_config[[method]][["plot_args"]]
# normalize the data
target_demoData = do.call(normalize, c(list(data = demoData[1:10]), mcn))
# get the plot
boxplot(assayDataElement(
demoData[1:10], elt=mcp[["toElt"]],col = mcp[["col"],main = mcp[["main"]],
log = "y", names = 1:10, xlab = "Segment",ylab = mcp[["ylab"]]
)
}
Again, using this approach is not as flexible as ... (and consider splitting into two functions.. one that returns normalized data, and a second function that generates the plot..

Is there a way to highlight multiple clades of an unrooted phylogenetic tree using one geom_highlight() layer and "type='encircle'"?

This is my first post so please tell me if I am breaking your rules! My problem is described in the comments of this simplified version of my code.
I want to plot an unrooted phylogenetic tree that neatly highlights selected clades.
I like the results of using geom_hilight() from ggtree with type = 'encircle', but I do not like having to individually edit the node and color values for every input. (see method 1)
method 2 is close to what I want, but with the wrong highlight type (roundrect)
method 3 uses the correct highlight type (encircle) but returns an error.
# I don't think all of these packages are needed to reproduce this problem
library(ape)
library(dplyr)
library(GGally)
library(ggalt)
library(ggforce)
library(ggplot2)
library(ggtree)
library(tidyr)
library(tidytree)
library(treeio)
#my pipeline uses the output of RAxML. I made this simpler tree for discussion purposes.
sink("test.tree")
cat("((((((t24:0.8024311261,t11:0.7828436729):0.3048173019,(t21:0.4867131179,t18:0.2167164627):0.7519672168):0.5776117099,t5:0.4223263576):0.5963104749,(t17:0.1558260066,t20:0.41109852):0.09447153704):0.2661841849,((((t6:0.009324073093,t12:0.2732205035):0.7790091021,t10:0.08588226303):0.3282297731,t9:0.2075715209):0.664191803,(((t15:0.5832811284,t14:0.8461383074):0.6081165755,t19:0.5950602938):0.7095833826,t8:0.7146228608):0.7801561591):0.6674923887):0.654328516,(((t13:0.6356930537,t3:0.8536336934):0.8644152461,t2:0.1784738901):0.7129137593,t23:0.8907998055):0.3618239218,((t16:0.1825823467,t7:0.8856151809):0.4720220205,(t22:0.672613536,(t1:0.9215354125,(t4:0.9248593273,t25:0.5937075356):0.3007316259):0.6941311779):0.6789765966):0.2112918347);")
sink()
#import tree
tree1 <- read.tree("test.tree")
#choose root nodes and colors for highlighting clades
group.roots <- c(34, 28, 44, 41)
group.colors <- c("#fd00fe", "#62ce75", "#9a1073", "#4ad9e1")
#write a data frame
g <- data.frame(gnode = group.roots, gfill = group.colors)
#
tree1unrooted <- ggtree(tree1,layout = 'unrooted')
#method 1: I want my plot to look like this, but I do not want to use so many instances of "geom_hilight()"
tree1unrooted + geom_label(aes(label = node)) +
geom_hilight(
node = 34,
alpha = 1,
fill = "#fd00fe",
type = "encircle",
to.bottom = TRUE
) +
geom_hilight(
node = 28,
alpha = 1,
fill = "#62ce75",
type = "encircle",
to.bottom = TRUE
) +
geom_hilight(
node = 44,
alpha = 1,
fill = "#9a1073",
type = "encircle",
to.bottom = TRUE
) +
geom_hilight(
node = 41,
alpha = 1,
fill = "#4ad9e1",
type = "encircle",
to.bottom = TRUE
)
#method 2: I have used this method to highlight multiple clades successfully with "type = 'roundrect'", but the highlighed regions overlap.
tree1unrooted +
geom_hilight(
data = g,
mapping = aes(node = gnode, fill = gfill),
alpha = 1,
type='roundrect',
to.bottom = TRUE
)
#method 3: I need "type = 'encircle'" for my plot. This gives the error: "Error in FUN(X[[i]], ...) : object 'x' not found"
tree1unrooted +
geom_hilight(
data = g,
mapping = aes(node = gnode, fill = gfill),
alpha = 1,
type='encircle',
to.bottom = TRUE
)
This seems like a bug to me, since one wouldn't think changing the fill shape should cause an error when a different shape works with the same syntax.
It appears that the data passed to the geom_hilight layer gets merged with the plot data, and for some reason this step goes with the "encircle" shape.
Anyway, one obvious solution is to program a list of single geom_hilight layers and add that to the plot:
tree1unrooted +
lapply(seq(nrow(g)), function(i) {
geom_hilight(
node = g$gnode[i],
alpha = 1,
fill = g$gfill[i],
type = "encircle",
to.bottom = TRUE
)
})

labelling specific data points in graph R without ggplot

I am trying to label the data points which are shaded in the plot.
Here is my sample data :
genes logFC PValue
1 Arhgap8 -5.492152 2.479473e-99
2 Asns -2.519970 2.731718e-93
3 Bmp4 -1.663583 4.767201e-72
4 Casp1 -1.650139 2.212689e-25
5 Ctgf -1.272772 1.000103e-61
6 Eya4 -2.328052 2.077364e-68
my plot code till now :
plot(sample$logFC,-log10(as.numeric(sample$PValue)),pch = 20,xlab = 'Log2 FoldChange',ylab = '-Log10 p-value',col = 'blue',xlim = c(-10,8),ylim = c(0,300),cex.lab=1.5, cex.axis=1.5)
points(sample$logFC,-log10(as.numeric(sample$PValue)),col = "dark green")
with(subset(sample,genes=='Arhgap8'),points(logFC,-log10(as.numeric(PValue)),pch = 20, col="orange"))
I have tried using the below command including text;but it doesnt show me the label.
with(subset(sample,genes=='Arhgap8'),points(logFC,-log10(as.numeric(PValue)),pch = 20, col="violet"),text(sample,labels = sample$genes,cex = 0.9,pos = 4))
The correct way to use with to run to commands would be
with(subset(sample, genes=='Arhgap8'), {
points(logFC, -log10(as.numeric(PValue)), pch = 20, col="violet")
text(logFC, -log10(as.numeric(PValue)), labels = genes, cex = 0.9, pos = 4)
})
When you pass more arguments with with(), they are silently ignored. For example
with(iris, mean(Sepal.Length), stop("not run"))

Skip empty panel using lattice package, R programming

I want to skip a empty panel using lattice package in R.
set.seed(1)
df1 <- data.frame("treatment" = c(rep("A",16),rep("B",16),rep("C",16)),
"disease_type" = c(rep("1",8),rep("2",8)),
"days_after_application" = rep(c(rep("10-24",4),rep("24-48",4)),6),
"severity" = rnorm(48, mean = 80, sd = 5))
df1[(df1$disease_type == "2" & df1$days_after_application == "24-48"),"severity"] <- NA
library(lattice)
figure1 <- bwplot(treatment~severity|days_after_application+disease_type,
data = df1,layout = c(2,2),
strip = strip.custom(strip.names = TRUE))
jpeg("figure1.jpeg")
print(figure1)
dev.off()
Here is what I get
My question is how I can remove/skip empty panel in the top right WITHOUT changing layout?
I have tried following code. However, it doesn't work.
figure2 <- bwplot(treatment~severity|days_after_application+disease_type,
data = df1,layout = c(2,2),
strip = strip.custom(strip.names = TRUE),
skip = c(FALSE,FALSE,FALSE,TRUE))
jpeg("figure2.jpeg")
print(figure2)
dev.off()
Here is what I got
I also tried following codes. But it is not what I want since I do want 2 levels strips.
df1[(df1$disease_type == "2" & df1$days_after_application == "24-48"),] <- NA
bwplot(treatment~severity|interaction(days_after_application,disease_type),
data = df1,layout = c(2,2),
strip = strip.custom(strip.names = TRUE))
Thank you!
Get help from a Professor in Temple University.
Here is his solution:
figure4 <- bwplot(treatment~severity|days_after_application+disease_type,
data = df1,layout = c(2,2),
strip = strip.custom(strip.names = TRUE),
skip = c(FALSE,FALSE,FALSE,TRUE),
scales=list(alternating=FALSE), ## keep x-scale on bottom
between=list(x=1, y=1)) ## space between panels
pdf("figure4%03d.pdf",onefile = FALSE) ## force two pages in file.
print(figure4)
dev.off()

R: Get quantmod's chartSeries and AddTA to not show last value

When using chartSeries, by default it also shows on the top left of the plot the last value. Is there any way to prevent it from doing it?
When adding a new TA with addTA, you can avoid the last value on the plot by setting the argument legend = "", but only if you're making a new plot for the TA. If the TA is on a previously plotted graphic, it'll show the last value regardless of what you put in the legend argument.
getSymbols ("AAPL", src = "google")
chartSeries(AAPL)
What can I use here to prevent it from printing the last value on the plot?
addTA(EMA(Cl(AAPL)), on = 1, legend = "")
This still prints the last value on the top left of the plot. The weird part is that it doesn't do it if you're plotting on a new plot like this:
addTA(EMA(Cl(AAPL)), legend = "")
Is it like this by default, or is there something I can do to get around it?
The last value is shown by default (yes, annoyingly). You'll likely have to modify the source code to remove the last number showing in addTA.
I don't use addTA, but rather add_TA and chart_Series, because I think they look much better (second generation charts for quantmod). Here is a solution that removes the last number from showing for the add_TA version. But you must be willing to modify the source code.
In add_TA, you'll need to modify approximately lines 56-60 of the source:
Replace the text.exp, which is this:
# this is inside add_TA:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(1, 1 + strwidth(name)),
y = 0.3, labels = c(name, round(last(xdata[xsubset]),
5)), col = c(1, col), adj = c(0, 0), cex = 0.9,
offset = 0, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
with these modifications:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(strwidth(name)), # <- affects label on the subchart
y = 0.3, labels = name, col = c(col), adj = c(0), cex = 0.9,
offset = 1, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
expr = TRUE)
...
and assign this modified code to a new variable, called say add_TA.mine:
add_TA.mine <- function (x, order = NULL, on = NA, legend = "auto", yaxis = list(NULL,
NULL), col = 1, taType = NULL, ...)
{
lenv <- new.env()
lenv$name <- deparse(substitute(x))
lenv$plot_ta <- function(x, ta, on, taType, col = col, ...) {
xdata <- x$Env$xdata
....
[all the code for the rest of the function with modifications]....
}
}
plot_object
}
Now, just run the code with the modified function
library(quantmod)
getSymbols("AAPL")
environment(add_TA.mine) <- environment(get("add_TA", envir = asNamespace("quantmod")))
assignInNamespace(x = "add_TA", value = add_TA.mine, ns = "quantmod")
chart_Series(AAPL, subset = "2017")
add_TA(RSI(Cl(AAPL)))
quantmod:::add_TA(RSI(Cl(AAPL)))
You can see the last value is no longer printed:
(You could make the same kinds of changes in the old addTA code (perhaps via chartSeries if you really want to stick to the old plots)
If you're happy with the changes, and want to make them permament in add_TA, you can recompile the quantmod source code yourself with your modifications (i.e. you need to download the quantmod source code and recompile the package) . If you make a mess of things you can always redownload the original quandmod source code again.

Resources