Plotly chart is not displayed in Shiny app - r

I am trying to implement an option with a drop-down menu in a simple Shiny application. With this drop-down list, you can choose between two charts. The first chart is prepared with the ggplot2 library, while the second is with the Plotly library. Below you can see my code :
---
title: "Test App"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(plotly)
# Data
data <- mtcars
data$cyl <- as.factor(data$cyl)
```
Column {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("clusterNum",
label = h4("Charts"),
choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"),
selected = "Chart1"
)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart
```{r}
Chart1 <- ggplot(data, aes(x = wt, y = mpg)) +
geom_point()
Chart2 <- plot_ly(data, x = ~wt, y = ~mpg, type = 'bar')
renderPlot({
switch(input$clusterNum,
"Chart1" = Chart1,
"Chart2" = Chart2
)
})
```
After executing this code, I saw that Chart 1, which was prepared with ggplot2, works well, while Chart 2 with Plotly is not displayed. So can anybody help me how to solve this problem and to see Chart 2 after selection with the drop-down list?

To render the plotly chart you have to use renderPlotly, while for the ggplot we have to stick with renderPlot. As a consequence switching conditionally between the two render functions requires some more effort and involves wrapping in renderUI and displaying the chart via uiOutput:
---
title: "Test App"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(plotly)
# Data
data <- mtcars
data$cyl <- as.factor(data$cyl)
```
Column {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("clusterNum",
label = h4("Charts"),
choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"),
selected = "Chart1"
)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart
```{r}
Chart1 <- ggplot(data, aes(x = wt, y = mpg)) +
geom_point()
Chart2 <- plot_ly(data, x = ~wt, y = ~mpg, type = 'bar')
```
```{r}
observeEvent(input$clusterNum, {
output$plot <- switch(input$clusterNum,
"Chart1" = renderUI({renderPlot(Chart1)}),
"Chart2" = renderUI({renderPlotly(Chart2)})
)
})
uiOutput("plot")
```

Related

Changing values in Shiny

I am trying to implement a slider in a very simple Shiny application. The main idea is to change the values with the slider and see the visualized result in Chart 2. Below you can see my code
---
title: "Test App"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
# Data Set 1
df<-data.frame( cyl=c("4","6","8"),
Multiplier=c(2,4,6))
# Data Set 2
df1 <- mtcars
df1$cyl <- as.factor(df1$cyl)
```
Column {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("clusterNum",
label = h4("Charts"),
choices = list("Chart1" = "Chart1", "Chart2" = "Chart2"),
selected = "Chart1"
)
# Sidebar to demonstrate various slider options ----
sidebarPanel(
# Input: Simple integer interval ----
sliderInput("integer", "Integer:",
min = 0, max = 8,
value = 1),)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart
```{r}
# First chart
Chart1 <- ggplot(df1, aes(x = wt, y = mpg)) +
geom_point()
# Second chart
Chart2_df1<-df1%>%
dplyr::left_join(df,df1,by = c("cyl"="cyl"))
Chart2_df1<-Chart2_df1%>%
dplyr::mutate(mpg_new=(mpg*Multiplier))
Chart2 <- ggplot(Chart2_df1, aes(x = wt, y = mpg_new)) + geom_point()
# Visualization of the selected chart
renderPlot({
switch(input$clusterNum,
"Chart1" = Chart1,
"Chart2" = Chart2
)
})
```
With the values from the slider, I want to change the value in df for column Multiplier. These values, after changing, are part of the formula of the second chart for multiplying with the value from df1, with column mpg. After this operation, the next step is showing result on chart 2.
So can anybody help me how to implement this similar as picture below ?
In order for the plot to be reactive to an input, we need it to be within reactive or processing within the renderPlot (which is reactive in nature).
One way to do this is to make Chart2 a reactive plot, and then "call" it with Chart2() (the way to get at reactive data/plots):
# First chart
Chart1 <- ggplot(df1, aes(x = wt, y = mpg)) +
geom_point()
# Second chart
Chart2 <- reactive({
dplyr::left_join(df, df1, by = c("cyl" = "cyl")) %>%
dplyr::mutate(mpg_new = (mpg * Multiplier * input$integer)) %>%
ggplot(aes(x = wt, y = mpg_new)) +
geom_point()
})
# Visualization of the selected chart
renderPlot({
switch(input$clusterNum,
"Chart1" = Chart1,
"Chart2" = Chart2()
)
})
Note that Chart1 is unmodified, and since it is not a reactive component, we continue to reference it as Chart1 (no ()) just as we would any other regular R object. Since Chart2 is a shiny-reactive object, though, we need the () to get at the updated value.
If you will be doing something with this data in addition to plotting it, one might choose to make the altered data available as one reactive component and then use it in the other(s).
# Second chart data
Chart2_dat <- reactive({
dplyr::left_join(df, df1, by = c("cyl" = "cyl")) %>%
dplyr::mutate(mpg_new = (mpg * Multiplier * input$integer))
})
# Second chart
Chart2 <- reactive({
Chart2_dat() %>%
ggplot(aes(x = wt, y = mpg_new)) +
geom_point()
})
# Visualization of the selected chart
renderPlot({
switch(input$clusterNum,
"Chart1" = Chart1,
"Chart2" = Chart2()
)
})
and any other components (e.g., tables, additional plots) can also use Chart2_dat() to see the joined/updated data.

Making subtabs in flexdashboard application

Below you can see my test application which I built in R with flexdashboard library (pics+code)
---
title: "Test APPLICATION"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
---
```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(plotly)
library(data.table)
library(tidyr)
library(dplyr)
library(tidyverse)
library(reshape)
library(knitr)
library(DT)
library(rpivotTable)
library(openintro)
library(DataCombine)
library(viridisLite)
library(eurostat)
library(tidyquant)
library(scales)
library(OECD)
library(lubridate)
library(wbstats)
library(OECD)
require(scales)
library(ggplot2)
library(dplyr)
library(openintro)
library(DataCombine)
library(viridisLite)
library(eurostat)
library(tidyquant)
library(scales)
library(readxl)
library(dplyr)
library(zoo)
library(rsconnect)
library(tidyverse)
library(tidyr)
library(data.table)
data=mtcars
data$cyl <- as.factor(data$cyl)
```
# Intro {.sidebar}
Testing application
PART 1
=======================================================================
Row {.tabset}
-----------------------------------------------------------------------
### Notes
**DIFFERENT TYPES OF CARS**
- Names:
- Consumption:
- Number of cylinders
### Tab 1
```{r,eval=TRUE}
rpivotTable(
data,
aggregatorName = "Integer Sum",
vals="mpg",
cols = "Car Parametars",
width="150%",
height="400px",
rendererName = "Table", buttons=c('copy','csv','excel','pdf','print'))
```
PART 2
=======================================================================
Row
-----------------------------------------------------------------------
### Cars 1
```{r,eval=TRUE}
fig<-qplot(x = data$wt, y = data$mpg)
fig
```
### Cars 2
```{r,eval=TRUE}
fig<-qplot(data$cyl, geom = "bar")
fig
```
Row {.tabset}
-----------------------------------------------------------------------
### Cars 3
```{r,eval=TRUE}
fig<-ggplot(data, aes(x=hp, y=mpg, color=cyl, shape=cyl)) +
geom_point(size=3)
fig
```
### Cars 4
```{r,eval=TRUE}
plt <-ggplot(data, aes(x=hp, y=mpg, color=cyl, shape=cyl)) +
geom_point(size=3) +
geom_smooth(method="lm", aes(fill=cyl))
plt + facet_wrap(~cyl)
```
Now I want to divide Tab 1. into two separate subtabs, Tab 1a and Tab 1b. Those subtabs need to be placed below Tab 1.
Tab 1 is the existing table from Tab 1, while Tab 1B is the graphs from Part 2.
After adding these tabs final output must be as in the picture below.
So can anybody help me with how to solve this problem?

How do I stop the code from showing on my R dashboards when I publish them

So im trying to create a dashboard however, whenever I load the dashboard there is code on the dashboard and you can only see half of the chart . I'm unsure where the error is occurring and why the dashboard looks like it does. How do I make it show only the chart is shown and not the code?
```
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org")
p_load(tidyverse, ggthemes, magrittr, lubridate, tidyquant, gridExtra,flexdashboard, knitr, RColorBrewer, hrbrthemes, anytime, plotly)
library(flexdashboard)
Grammy <- read_csv("Grammy.csv") |> rename("Brandi Carlile" = "Brandi Carilie")
Grammy$Date <- strptime(Grammy$Date, format="%m/%d/%Y %H:%M")
Grammy <- mutate(Grammy, Date = as.Date(Grammy$Date, "%m/%d/%Y"))
Grammy$Date <-anydate(Grammy$Date)
Grammy$Date <- as.Date(Grammy$Date)
Grammy$Date<- as.Date(Grammy$Date) #convert to date
Grammylonger <- Grammy |>
pivot_longer(cols = `Brandi Carlile`:`Silk Sonic`, names_to = "Artists", values_to = "Streams")
Page 1
=====================================
Column {data-width=650}
-----------------------------------------------------------------------
### Chart A
```{r}
p <- ggplot(data = Grammy, aes(x=Date, y=`Brandi Carlile`)) +
geom_line()+
geom_point()+
scale_x_date(date_breaks = "1 day", date_labels = "%b %Y") +
scale_y_continuous(breaks=seq(3000000, 4000000, 10000))
ggplotly(p)
```
you can add this argument to the quotation code mark
```{r warning=TRUE, include=FALSE}
```
This will hide the code and the warning message if happen
If I'm understanding your question correctly, try setting {r echo = FALSE}

plots not showing in flexdashboard tabs

When I render the flexdashboard the plotly chart only shows on the first tab, and not on the remaining tabs. The reproducible example below uses the flexdashboard example for .tabset use. I am running R 3.6.1
I have used plotly and tabset in the past, and I am not sure why it is not working now.
---
title: "Tabset Column"
output: flexdashboard::flex_dashboard
---
Column
-------------------------------------
### Chart 1
```{r}
library(ggplot2)
library(plotly)
library(dplyr)
da <-data.frame(ns=rep(0:1,6), month=factor(1:12), a=letters[1:12])
p <- ggplot(da) +
geom_bar(aes(x=month,y=ns,fill=ns),stat = "identity") +
facet_wrap(~a )+
theme_bw(12) + ylab("CYER") +
scale_fill_viridis_c(option="D",direction = -1)
p2 <- ggplot(da) +
geom_bar(aes(x=month,y=ns,fill=ns),stat = "identity") +
facet_wrap(~a )+
theme_bw(12) + ylab("CYER") +
scale_fill_viridis_c(option="C",direction = -1)
```
Column {.tabset}
-------------------------------------
### Chart 2
```{r}
ggplotly(p2)%>%layout(
margin = list(b = 100, l = 100,r = 150))
```
### Chart 3
```{r}
ggplotly(p)%>%layout(
margin = list(b = 100, l = 100,r = 150))
```

Variable plot height within single chunk

The following knitr thingy produces multiple plots via lapply. Their number and content therefore varies depending on the preceding R code.
Is there a way to set the plot height individually for each plot using a variable (like the height of the highest bar in a given bar chart)?
---
title: "Variable plot height"
output: word_document
---
Plots:
```{r, echo=FALSE, fig.height = 2}
library(ggplot2)
library(tidyr)
data(mtcars)
mtcars$car = row.names(mtcars)
cars = gather(mtcars[1:5, ], variable, value,
-c(car, mpg, disp, hp, qsec))
lapply(unique(cars$car), function(x) {
ggplot(cars[cars$car == x, ], aes(variable, value)) +
geom_bar(stat = "identity")
})
```
One way would be to create each image and include it into the document as an external image. You can employ the power of "asis". Here's a small example.
---
title: "Untitled"
author: "Neznani partizan"
date: "04. december 2015"
output: html_document
---
```{r, echo=FALSE, fig.height = 2}
library(ggplot2)
library(tidyr)
data(mtcars)
mtcars$car = row.names(mtcars)
cars = gather(mtcars[1:5, ], variable, value,
-c(car, mpg, disp, hp, qsec))
suppressMessages(invisible(lapply(unique(cars$car), function(x) {
ggplot(cars[cars$car == x, ], aes(variable, value)) +
geom_bar(stat = "identity")
ggsave(sprintf("%s.png", x))
})))
```
```{r results = "asis", echo = FALSE}
cat(sprintf("<img src='%s' alt='' style='width:350px;height:228px;'> <br />",
list.files(pattern = ".png", full.name = TRUE)))
```
Image sizes can be adjusted on-the-fly using appropriate arguments in ggsave and/or in printing HTML code.
The fig.width and fig.height chunk options can take in multiple values. In your example, there are five plots, so by setting a numeric vector of length five for the widths and heights, and saving the list of ggplot objects, you can have one chunk produce five graphics of different sizes in the final document. An example .Rmd file is below.
---
title: "Variable plot height"
output: word_document
---
Plots:
```{r, echo=FALSE}
library(ggplot2)
library(tidyr)
data(mtcars)
mtcars$car = row.names(mtcars)
cars = gather(mtcars[1:5, ], variable, value, -c(car, mpg, disp, hp, qsec))
plots <-
lapply(unique(cars$car), function(x) {
ggplot(cars[cars$car == x, ], aes(variable, value)) +
geom_bar(stat = "identity")
})
widths <- c(3, 4, 5, 3, 6)
heights <- c(3, 3, 3, 4, 3)
```
```{r show_plots, fig.width = widths, fig.height = heights}
plots
```

Resources