I'm trying to plot some (interactive) highcharts plots for some quantmod works. Plots (in R-studio viewer tab) works fine when I "run" them. or polts then interactively on the console window, but shows nothing when I source the whole program.
How can I source the whole script and get all the plots in the viewer window?
How can I save the plots (from the script) to a pdf file?
thanks.
code example:
library(quantmod)
library(highcharter)
SPY <- getSymbols("SPY", from = Sys.Date() - lubridate::years(3), auto.assign = FALSE)
SPY <- adjustOHLC(SPY)
SPY.EMA.20 <- EMA(Cl(SPY), n = 20)
SPY.EMA.50 <- EMA(Cl(SPY), n = 50)
SPY.RSI.14 <- RSI(Cl(SPY))
SPY.RSI.SellLevel <- xts(rep(70, NROW(SPY)), index(SPY))
SPY.RSI.BuyLevel <- xts(rep(30, NROW(SPY)), index(SPY))
AAPL <- getSymbols("AAPL", from = Sys.Date() - lubridate::years(3), auto.assign = FALSE)
highchart(type = "stock") %>%
hc_add_series(AAPL, name = "AAPL", color = hex_to_rgba("red", 0.7))
hchart(AAPL)
highchart(type = "stock") %>%
hc_yAxis_multiples(
create_yaxis(3, height = c(3, 1, 1), turnopposite = TRUE)
) %>%
hc_add_series(SPY, yAxis = 0, name = "SPY", color = hex_to_rgba("red", 0.7)) %>%
hc_add_series(SPY.EMA.20, yAxis = 0, name = "EMA 20") %>%
hc_add_series(SPY.EMA.50, yAxis = 0, name = "EMA 50") %>%
hc_add_series(SPY$SPY.Volume, yAxis = 1, color = "gray", name = "Volume", type = "column", title = 'volume') %>%
hc_subtitle(yAxis = 1, text = "Volume", align = "left", style = list(color = "#2b908f", fontWeight = "bold")) %>%
hc_add_series(SPY.RSI.14, yAxis = 2, name = "Osciallator", color = hex_to_rgba("green", 0.7)) %>%
hc_add_series(SPY.RSI.SellLevel, yAxis = 2, color = hex_to_rgba("red", 0.7), name = "Sell level") %>%
hc_add_series(SPY.RSI.BuyLevel, yAxis = 2, color = hex_to_rgba("blue", 0.7), name = "Buy level")
Related
I'm trying to reproduce in R Plotly a 2 categorical variables violin plot that works just fine in ggplot2. But when I set the widths of the individual violins to be the same, using scalemode = "width", as described in the reference (https://plotly.com/r/reference/violin/), it simply wont work. Instead, it shows the widths (violin maximum) proportional to the counts in each category.
Here is an example:
# Paths:
path_data = "data/"
path_lib = "renv/library/R-4.1/x86_64-pc-linux-gnu/"
# Packages:
require(dplyr, lib = path_lib)
require(readr, lib = path_lib)
require(RColorBrewer, lib = path_lib)
require(plotly, lib = path_lib)
# Dataset:
df = readr::read_csv(paste0(path_data, "nasa_exoplanets.csv")) %>%
as.data.frame()
attr(df, "spec") = NULL
df_varnames = readr::read_csv(paste0(path_data, "nasa_exoplanets_var_names.csv")) %>%
as.data.frame()
attr(df_varnames, "spec") = NULL
# Variables:
cat_var1 = "st_metratio"
cat_var2 = "disc_locale"
cat_var_name1 = (df_varnames %>%
dplyr::filter(var == cat_var1))$var_name
cat_var_name2 = (df_varnames %>%
dplyr::filter(var == cat_var2))$var_name
num_var = "sy_dist"
num_var_name = (df_varnames %>%
dplyr::filter(var == num_var))$var_name
# Adapt the data:
df_plot = df %>%
dplyr::select(cat_var1,
cat_var2,
num_var)
# Deal with NA:
df_plot[which(is.na(df_plot[, cat_var1])), cat_var1] = "NA"
df_plot[which(is.na(df_plot[, cat_var2])), cat_var2] = "NA"
df_plot = df_plot[which(!is.na(df_plot[, num_var])), ]
# Levels order:
sorted_levels1 = sort(unique(df_plot[, cat_var1]))
df_plot[, cat_var1] = factor(x = df_plot[, cat_var1],
levels = sorted_levels1)
sorted_levels2 = sort(unique(df_plot[, cat_var2]))
df_plot[, cat_var2] = factor(x = df_plot[, cat_var2],
levels = sorted_levels2)
# Plot:
my_palette = colorRampPalette(c("#111539", "#97A1D9"))
n_levels2 = length(unique(df_plot[, cat_var2]))
p = plot_ly(
data = df_plot,
type = "violin",
x = ~eval(parse(text = cat_var1)),
y = ~eval(parse(text = num_var)),
color = ~eval(parse(text = cat_var2)),
colors = my_palette(n_levels2),
spanmode = "hard",
alpha = 1,
box = list(visible = FALSE),
meanline = list(visible = FALSE),
points = FALSE,
scalemode = "width" ### this doesn't work ###
) %>%
layout(
xaxis = list(
title = paste0("<b>", cat_var_name1, "</b>"),
titlefont = list(size = 20),
tickfont = list(size = 18),
categoryorder = "array"
),
yaxis = list(
title = paste0("<b>", num_var_name, "</b>"),
titlefont = list(size = 20),
tickfont = list(size = 18),
type = "log"
),
margin = list(
l = 10,
r = 10,
t = 10,
b = 10
),
legend = list(
title = list(
text = paste0("<br><b>", cat_var_name2, "</b>"),
font = list(size = 18)
)
),
hoverlabel = list(font = list(size = 16)),
showlegend = TRUE,
violinmode = "group"
)
p
data file: https://github.com/rafael747cardoso/Data_Visualization_Gallery/blob/main/data/nasa_exoplanets.csv
How it should be, plotted in ggplot2:
How it is with R Plotly:
I am trying to plot a scatter plot that when the mouse hovers over one of the points, an image, corresponding to a URL in the data appears.
Is it possible in R? it seems it is possible in python...
thanks,
Here is a solution using the Highchater package:
library(highcharter)
df <- data.frame(x = c(1, 2, 3, 4),
y = rep(0, 4),
package = c("dplyr", "shiny", "purrr", "stringr"),
urlimage = c("https://github.com/rstudio/hex-stickers/raw/master/PNG/dplyr.png",
"https://github.com/rstudio/hex-stickers/raw/master/PNG/shiny.png",
"https://github.com/rstudio/hex-stickers/raw/master/PNG/purrr.png",
"https://github.com/rstudio/hex-stickers/raw/master/PNG/stringr.png"))
hover_info <- tags$tr(
tags$th("Package"),
tags$td(paste0("{point.package}")),
tags$img(src = "{point.urlimage}", width = "125px", height = "125px")) %>%
as.character()
highchart() %>%
hc_add_series(data = df,
mapping = hcaes(x = x, y = y),
type = "scatter",
marker = list(radius = 5, symbol = "circle")) %>%
hc_tooltip(
useHTML = TRUE,
headerFormat = "<table>",
pointFormat = hover_info,
footerFormat = "</table>"
)
Output:
For example, reproduce by running:
library(plotly)
library(quantmod)
setDefaults(getSymbols,src='google')
getSymbols('AAPL',from="2010-01-01",to=Sys.Date())
df <- data.frame(Date = index(AAPL), coredata(AAPL))
colnames(df)
p <- df %>%
plot_ly(x = ~Date, type="candlestick",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low) %>%
layout(title = "Basic Candlestick Chart")
p
Now this plot does not have a vertical slider/range selector like plotly scatterplots do (say to zoom on a price and time range rather than just a time range as now). How to add one to it?
This can be done by changing xaxis in layout. Using piece of code from example:
rangeselectorlist = list(
x = 0, y = 0.9,
bgcolor = "#0099cc",
font = list(color = "white"),
buttons = list(
list(count = 1, label = "reset", step = "all"),
list(count = 1, label = "1yr", step = "year", stepmode = "backward"),
list(count = 3, label = "3 mo", step = "month", stepmode = "backward"),
list(count = 1, label = "1 mo", step = "month", stepmode = "backward"),
list(step = "all")
)
)
and adding to
p <- df %>%
plot_ly(x = ~Date, type="candlestick",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low) %>%
layout(title = "Basic Candlestick Chart",
xaxis = list(rangeslider = list(visible = F),
rangeselector = rangeselectorlist) )
p
adds vertical slider/range selector.
I'm plotting a financial intra-day time serie on an R-Shiny project using the highcharter package. I'm using the following code for the server part in order to get the output (note that xtsPrices() is a function that returns an xts intraday time-serie):
output$plot <- renderHighchart({
y <- xtsPrices()
highchart() %>%
hc_exporting(enabled = TRUE)%>%
hc_add_series_ohlc(y) %>%
hc_add_theme(hc_theme_538(colors = c("red", "blue", "green"),
chart = list(backgroundColor = "white") ))
})
I read in the documentation that in order to personalize zoom buttons I have to deal with the hc_rangeSelector() function, but I don't understand how to specify them in this R-Shiny environment as shown for the javascript case in Highstock API. In particular - because it's an intra-day time-serie - I would need buttons like "20min", "1h", "3h", "1D", etc.
For intra-day data you can do something like this:
hc <- highchart() %>%
hc_exporting(enabled = TRUE) %>%
hc_add_series_ohlc(y, yAxis = 0, name = "Sample Data", id = "T1",smoothed=TRUE,forced=TRUE,groupPixelWidth=24) %>%
hc_rangeSelector( buttons = list(
list(type = 'all', text = 'All'),
list(type = 'hour', count = 2, text = '2h'),
list(type = 'hour', count = 1, text = '1h'),
list(type = 'minute', count = 30, text = '30m'),
list(type = 'minute', count = 10, text = '10m'),
list(type = 'minute', count = 5, text = '5m')
)) %>%
hc_add_theme(hc_theme_538(colors = c("red", "blue", "green"),chart = list(backgroundColor = "white") ))
hc
I'm trying to add horizontal and vertical lines in a highchart (rcharts) in a revealjs presentation.
I tried to modify the code of this post in this way:
require(xlsx)
library(rCharts)
Perhplot.df <-read.xlsx("C:\\RDirectory\\AREALAVORO\\JOB\\RISULTATI2.xlsx", sheetName="completo2")
lDf <- split(Perhplot.df, Perhplot.df$variable)
h16 <- hPlot(protection ~ days, data = lDf$Exposure,
type = "bubble",
group = "label",
title = "By Days of Exposure",
subtitle = "Move the mouse pointer on the bubbles to view the data",
size = "cluster_size",
group = "label")
h16$set(width = 1000, height = 600)
ord <- c("Less than 1 week"=0,
"1-2 weeks"=1,
"3-4 weeks"=2,
"More than 4 weeks"=3,
"Mean"=4
)
h16$params$series <- lapply(h16$params$series, function(d){
temp = ord[d$name]
names(temp) = NULL
d$legendIndex = temp
return(d)
})
h16$yAxis(min = 35, max = 70, title = list(text = "Level of Protection"))
h16$xAxis(min = 0, max = 45, title = list(text = "Days of Exposure"))
dfy<-data.frame(y=c(35,58,70), x=c(18.8,18.8,18.8))
h16$layer(y~x,data=dfy,type="line",color=list(const = 'darkblue'))
h16$show('inline', include_assets = TRUE)
the bubble plot is ok but then I try to add the vertical line I have this error:
Error in envRefInferField(x, what, getClass(class(x)), selfEnv) : ‘layer’ is not a valid field or method name for reference class “Highcharts”
So the solution works for Dimple Charts but not for Highcharts...
As same as rcharts highcharts plotLines.
You need to use plotLines argument:
library("rCharts")
# Some data
x <- abs(rnorm(10))
# A graph with column
h <- Highcharts$new()
h$chart(type = "column")
h$series(data = x)
h$xAxis(categories = letters[1:10])
# the horizontal line
h$yAxis(title = list(text = "rnorm()"),
plotLines = list(list(
value = mean(x),
color = '#ff0000',
width = 3,
zIndex = 4,
label = list(text = "mean",
style = list( color = '#ff0000', fontWeight = 'bold' )
))))
h
Yo add vertical you change yAxis by xAxis.
Or if you use highcharter (It's a new wrapper of highcharts for R):
h2 <- highchart() %>%
hc_chart(type = "column") %>%
hc_add_serie(data = x) %>%
hc_xAxis(categories = letters[1:10]) %>%
hc_yAxis(title = list(text = "rnorm()"),
plotLines = list(list(
value = mean(x),
color = '#ff0000',
width = 3,
zIndex = 4,
label = list(text = "mean",
style = list( color = '#ff0000', fontWeight = 'bold' )
))))
h2
Source: http://jkunst.com/highcharter/highcharts-api.html#hc_xaxis-and-hc_yaxis