nPLot x-axis Date variable and default stacked Bar plot in rCharts - r

I am using nPlot, my X-axis is Date variable, I want this to just Date as in my data 'YYYY-MM-DD', tilted vertically (90 degrees). I want nPlot show the chart stacked by default. Please help me out.
output$testChart = renderChart({
testChart = nPlot(Count~Date, data = df, group = 'Category',
type = 'multiBarChart')
testChart$chart(reduceXTicks = F)
testChart$xAxis(staggerLabels = T)
testChart$chart(stacked = T)
testChart$xAxis(tickFormat = "#! d3.time.format('%Y-%m-%d') !#")
return(testChart)
})
and in server.R
output$mytabs = renderUI({
tabs = tabsetPanel(
tabPanel('Tab1', h5("Tab1"),
fluidRow(showOutput("testChart"))
)
)
mainPanel(tabs)
})
in ui.R
uiOutput('mytabs')

Suppose that you stored your plot in the object n1. Here is how you can customize it do what you seek.
n1$chart(stacked = TRUE)
n1$xAxis(
tickFormat = "#! d3.time.format('%Y-%m-%d') !#",
rotateLabels = 90
)
n1
I have no way to verify that this works. So I would suggest that you post your data and the code that you used to generate this plot. Doing so, even this works for you, would be useful as it would help others who come across this question.

Related

Can’t display error bars with Plotly and Shiny

I’m trying to display error bars on a scatter plot with Shiny and plotly. Here’s my code in my server.R file:
data = reactiveVal()
observe({
results <- data.frame() # actually getting the data from here
# formatting output
final.results <- cbind(
"id" = paste(results$a,
results$b,
results$c,
sep = '-'),
"sigma" = sprintf("%.5g", results$s),
"c-e" = sprintf("%.3g",results$calc - results$exp)
)
data(final.results)
})
output$plot <- renderPlotly(
as.data.frame(data()[,c("id", "c-e", "sigma")]) %>% plot_ly(
x = ~`c-e`,
y = ~id,
height = 800,
type = 'scatter',
mode = 'markers',
marker = list(color = "#90AFD9"),
error_x = list(array = ~sigma, color = "#000000", type = "data")
)
)
The plot is ok except it’s not showing the error bars, what’s my mistake ?
EDIT: clarification for the origin of the data() function and what it’s return value is.
Thesprintf() function returns a character string, not a number, that is why it is not displaying the sigma values as error bars. If you want to keep 5 decimal places, use the round() function instead:
"sigma" = round(results$s, digits = 5)

How to change the y in flexdashboard selectInput

I'm trying to make a flexdashboard using IMDb data, that has an interactive jitter plot where you can change the x and y for visualizing hierarchical clustering result. The code that I've already made can change only the x and number of k. I think I should use reactive function but I don't really understand in using that. I've already tried many other ways from youtube and some documentary but still can't change the y. Here is layout of my dashboard, The y stuck at the runtime variable
data=df %>%
select(Rating, Votes, Gross, Runtime, Metascore)
selectInput("x", label = "X : ",choices = names(data))
selectInput("y", label = "Y : ",choices = names(data))
sliderInput('k',"Cluster",min = 2,max = 10, value = 6)
selectedData=reactive({
data %>% select(input$x, input$y)
})
data_scaled=scale(data)
dist_data=dist(data_scaled, method='euclidean')
hc_data=hclust(dist_data, method = "average")
renderPlot({
ggplot(selectedData(),
aes(x=!!rlang::sym(input$x), y=!!rlang::sym(input$y),
col=factor(cutree(hc_data, k=input$k))))+
geom_jitter(size=5, alpha=0.5 )+
labs(col="Cluster")
})
Here is an alternative example that seems to work, using the diamonds dataset from ggplot2. My guess is that the scaling and clustering steps take so long to run that the the y reactive only appears not to work. I would suggest pre-processing your data if app run times are a problem.
data=diamonds[1:1e3,] %>%
dplyr::select(where(is.numeric))
selectInput("x", label = "X : ",choices = names(data))
selectInput("y", label = "Y : ",choices = names(data))
sliderInput('k',"Cluster",min = 2,max = 10, value = 6)
data_scaled=scale(data)
dist_data=dist(data_scaled, method='euclidean')
hc_data=hclust(dist_data, method = "average")
renderPlot({
ggplot(data,
aes(x=!!rlang::sym(input$x), y=!!rlang::sym(input$y),
col=factor(cutree(hc_data, k=input$k))))+
geom_jitter(size=5, alpha=0.5 )+
labs(col="Cluster")
})

Selecting point with shiny and plotly

I have been trying for some time to debug my Shiny gadget but still cannot manage it. Really appreciate any help.
My gadget consists of a scatterplot generated with Plotly. The user can click one of the points, which will allow you to change some parameters associated with that point. To emphasise the fact that the user has selected that point, I wanted to highlight the selected point.
Alternatively, the user can also select a point from a dropdown menu, which also should highlight the corresponding point.
As an added feature, I want to additionally highlight points that are below a certain threshold on the x axis. This threshold is represented by a dotted line, which you can turn on and off, and move the value of the threshold.
In summary, the points on the plot should all be blue circles, except for the following two cases:
if it is clicked, i.e. it is the "active point" (this should create a red border around the point)
if it is below the threshold on the x-axis (the point should turn to an orange square)
If it is active AND below the threshold, it should be an orange square with a red border, as you would expect.
My gadget works, kind of. But in some cases not. In the example below, one of the points is already below the threshold, but when I select that point, the red marker appears on another point! Despite the active variable being the correct one.
I also get a weird behaviour that the points turn purple if the threshold is below all of the points. But if I move the threshold to be above one of the points, the colours are corrected.
I have a suspicion that this is something to do with the points being on different traces? Therefore when I try to highlight certain points, perhaps I am not indexing the vector as I am expecting. But I am finding it really difficult to debug inside Shiny and Plotly, and I have no good understanding of the Plotly object, so I don't have much clue as to what is going on.
The code below is a reproducible example. You have to run "dat1" through the "rew8r" function. I have taken out other features of the app to try to focus on the problem. Thanks very much to anyone who might take the time to have a look at this, and give any hints!
library(plotly)
library(dplyr)
library(shiny)
library(reactable)
dat1 <- data.frame(
Indicator = c("v1","v2","v3"),
Weight = rep(1,3),
Correlation = c(0.1, 0.8, 0.6) )
rew8r <- function(dat){
# get indicator names
inames <- dat$Indicator
## Create the shiny UI layout
ui <- fluidPage(
# the side panel
sidebarPanel(
selectInput("vseldrop", "Select indicator here or by clicking a point on plot.",
c("<Select>",inames)),
hr(style = "border-top: 1px solid #000000;"),
fluidRow(
column(6,numericInput("locorval", "Low correlation threshold:", 0.2, min = -1, max = 1, step = 0.05)),
column(6,br(),checkboxInput("locorsw", "Enable", value = FALSE)))
),
# the main panel (graph, table, etc)
mainPanel(
plotlyOutput("corrplot"),
textOutput("info")
)
)
## Create the Shiny Server layout
server <- function(input, output, session) {
# this is the plotly click data
event.data <- reactive({event_data(event = "plotly_click", source = "scplot")})
# First, monitor which variable is active
# Create reactive value for active var
acvar <- reactiveVal(NULL)
# update active variable via plot click
observeEvent(event.data(),{
acvar(event.data()$key)})
# update active variable via dropdown
observeEvent(input$vseldrop,
acvar(input$vseldrop))
## Create the plotly plot that compares price vs scoops
output$corrplot <- renderPlotly({
# colours around markers when selected or not
lincol <- ifelse(inames %in% acvar(), "red", "blue")
# size of line around marker (set to 0 if not selected)
linsize <- ifelse(inames %in% acvar(), 3, 0)
# symbol when above/below corr threshold
symbs <- if(input$locorsw==TRUE){c(16,15)}else{c(16,16)}
# colour when above/below threshold
pcols <- if(input$locorsw==TRUE){c("blue", "orange")}else{c("blue", "blue")}
# generate main plot
p <- plot_ly(dat, x = ~Correlation, y = ~Weight, type = "scatter", mode = "markers",
text = ~Indicator, key = ~Indicator, source = "scplot",
marker = list(size = 10, line = list(color = lincol, width = linsize)),
symbol = ~Correlation < input$locorval, symbols = symbs,
color = ~Correlation < input$locorval, colors = pcols) %>%
layout(showlegend = FALSE, yaxis = list(
range = c(0, 1.25),
autotick = FALSE,
dtick = 0.25),
xaxis = list(
range = c(-0.5, 1),
autotick = FALSE,
dtick = 0.2))
# add low correlation line, if activated
if(input$locorsw==TRUE){
p <- p %>% add_segments(x = input$locorval, xend = input$locorval, y = 0, yend = 1.25,
marker = list(color = 'red', opacity=0),
line = list(dash = 'dash')) %>%
layout(showlegend = FALSE)
}
p
})
# Text info
output$info <- renderText({
paste(acvar(), class(acvar()))
})
# update dropdown menu
observeEvent(acvar(),{
updateSelectInput(session, "vseldrop", selected = acvar())
})
}
runGadget(ui, server, viewer = browserViewer())
}

R Shiny HTMLWidget for interactive 3D-histograms

I would like to include a 3D dynamic (i.e. one can change its perspective just by moving the plot) histogram widget in a R Shiny application.
Unfortunately I didn't find any until now.
So far the results of my searches: with threejs (e.g. here on CRAN and there on GitHub) one can use many different representations (scatterplots, surfaces, etc.) but no 3D histogram. plot3D and plot3Drgl don't have any R Shiny counterpart.
Unless something already exists my intention is to create an HTMLWidget from one of the sub-libraries of vis.js, namely graph3d.
What are your views on this issue?
Best regards,
Olivier
It's possible with plot3Drgl. Here is an example.
library(plot3Drgl)
library(shiny)
options(rgl.useNULL = TRUE)
ui <- fluidPage(
rglwidgetOutput("myWebGL")
)
server <- function(input, output) {
save <- options(rgl.inShiny = TRUE)
on.exit(options(save))
output$myWebGL <- renderRglwidget({
try(rgl.close())
V <- volcano[seq(1, nrow(volcano), by = 5),
seq(1, ncol(volcano), by = 5)] # lower resolution
hist3Drgl(z = V, col = "grey", border = "black", lighting = TRUE)
rglwidget()
})
}
shinyApp(ui, server)
My package graph3d is on CRAN now.
library(graph3d)
dat <- data.frame(x = c(1,1,2,2), y = c(1,2,1,2), z = c(1,2,3,4))
graph3d(dat, type = "bar", zMin = 0, tooltip = TRUE)
You can customize the tooltips:
graph3d(dat, type = "bar", zMin = 0,
tooltip = JS(c("function(xyz){",
" var x = 'X: ' + xyz.x.toFixed(2);",
" var y = 'Y: ' + xyz.y.toFixed(2);",
" var z = 'Z: ' + xyz.z.toFixed(2);",
" return x + '<br/>' + y + '<br/>' + z;",
"}"))
)
I realize I have to add an option to control the size of the axes labels...
Many thanks, DSGym. I didn't know this library.
In my initial message (now amended) I actually forgot to mention the dynamic feature, i.e. the ability to change the perspective of the plot just by moving it with the mouse, like with vis.js-graph3d.
It seems plots from highcharter cannot do that, or am I mistaken?
[EDIT]: I just checked with Shiny: it is static.

Scale Y-Achsis in plotly candlestick chart

I am searching for a way to (auto-)scale the y-axis of a candlestick chart. If you take a look at the following example (from https://plot.ly/r/candlestick-charts/)
library(plotly)
library(quantmod)
getSymbols("AAPL",src='yahoo')
df <- data.frame(Date=index(AAPL),coredata(AAPL))
df <- tail(df, 365)
p <- df %>%
plot_ly(x = ~Date, type="candlestick",
open = ~AAPL.Open, close = ~AAPL.Close,
high = ~AAPL.High, low = ~AAPL.Low) %>%
add_lines(y = ~AAPL.Open, line = list(color = 'black', width = 0.75)) %>%
layout(showlegend = FALSE)
The y-axis has autoscal="normal", so it takes min and max from the dataset, but if you zoom, these values stay the same. It would be clearer for me to have the min and max of the current (zoomed/viewed) part of the graph
Until now i could not find a way to implement this feature, does anyone know a way to do so?
Amother solution for me would be just to get the "normal" zoom from charts like in this example:
library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
plot_ly(d, x = ~carat, y = ~price, color = ~carat,
size = ~carat, text = ~paste("Clarity: ", clarity))
Moving the slider within the candlestick chart is not autoscaling the y-axis for me either. Plotly team may not have solved it yet for candlesticks charts. autorange = TRUE is working neither.
But if anyone is using this in a shiny application, the workaround which can work is to have a date slider reactively connected to Plotly graph. The steps are as following:
create a date slider with a start and end selected
ui.R
...
uiOutput("dateSlider")
...
server.R
output$dateSlider <- renderUI({
sliderInput(
"dtSlider",
"Select a date range:",
min = min_date,
max = max_date,
value = c(max_date - 30, max_date), # in this case last 30 defines start and end
timeFormat = "%Y-%m-%d",
width = '80%'
)
output$dateSlider <- renderUI({
In the RenderPlotly section of server.R calculate a data.frame with data filtered from start to end using input$dtSlider[1] and input$dtSlider[2] correspondingly and then use the new reactively filtered data.frame in the Plotly code.
ui.R
plotlyOutput("candleChart")
server.R
output$candleChart <- renderPlotly({
...
df <- as.data.frame(dbFetch(res)) # querying DB to pull data with new input$dtSlider[1] as start and input$dtSlider[2] as end
...
fig <- df %>% plot_ly(x = ~timestamp, type="candlestick",
open = ~open, close = ~close,
high = ~high, low = ~low )
...
})
So now if we change the date slider, y-axis range changes automatically as shown below from same data.frame object:

Resources