I am trying to insert a bar graph from a dataset that I have into Shiny to make a simple bar graph of the data. This is my code thus far:
library(plotly)
library(shiny)
library(readxl)
excel_data <- read_excel(path = system.file("CHAMPdata_gender/datasets.xlxs", package = "readxl"))
ui <- fluidPage(
mainPanel(
plotlyOutput("chart")
)
)
server <- function(input, output, session) {
output$chart <- renderPlotly({
# write code here to read data from csv file
# Set x and y axis and display data in bar chart using plotly
p <- plot_ly( x = CHAMPdata_gender$X,
y = CHAMPdata_gender$Total.Respond, CHAMPdata_gender$Never, CHAMPdata_gender$Less.than.one.year, CHAMPdata_gender$One.year.or.more,
name = "Childhood data",
type = "bar")
})
}
shinyApp(ui, server)
I am currently trying to learn Shiny in R, so would appreciate all the help I can get! thanks
Related
I am trying to use plotly_relayout to get the x-axis zoom limits of one plot, and apply them to another plot in Shiny. So far I can get the relevant plotly_relayout data from "plot1" (x-axis limits), transform it (from a numeric to a Date), and have it available right before plotting "plot2", however it does not actually set the zoom extents on "plot2".
In most cases, my RStudio crashes as soon as I attempt to zoom in on "plot1". Only in the small number of cases when RStudio does not crash, do I see that the "coord_cartesian" in "plot2" is not having the desired effect (after making a zoom in plot1).
I am also rather curious if the persistent crashing of my RStudio is normal given the code below, or if I may need to consider a fresh rebuild of RStudio. Any ideas on how to achieve this effect would be appreciated!
library(ggplot2)
library(plotly)
library(shinydashboard)
library(shinyWidgets)
#Data frame with dates and bogus data
a=data.frame(Date=seq.Date(as.Date("2000-01-01"),
as.Date("2000-12-31"),
"day"),
value=rnorm(366)
)
#Simple dashboard with two plots
ui <- dashboardPage(
dashboardHeader(title="Sample App"),
dashboardSidebar(
),
dashboardBody(
plotlyOutput("plot1"),
plotlyOutput("plot2")
)
)
server <- function(input, output, session){
#Create a reactive list, set zoomX1 and zoomX2 as NULL
reactiveList <- reactiveValues(zoomX1=NULL,zoomX2=NULL)
#Create a reactive function to update the reactive list every time the plotly_relayout changes
relayout_data <- reactive({
xvals=event_data("plotly_relayout",source="plot1")
if (is.null(xvals$`xaxis.range[0]`)){
} else {
reactiveList$zoomX1=as.Date(xvals$`xaxis.range[0]`,origin="1970-01-01")
reactiveList$zoomX2=as.Date(xvals$`xaxis.range[1]`,origin="1970-01-01")
}
})
#Plot1, just plot all the data
output$plot1 <- renderPlotly({
g1=ggplot(a,aes(x=Date,y=value))+
geom_point()
ggplotly(g1,source="plot1") %>% event_register("plotly_relayout")
})
#Plot 2, same as Plot1, but should set the coord_cartesian based on plot1's current zoom level taken from the event_data("plotly_relayout")
output$plot2 <- renderPlotly({
relayout_data()
g1=ggplot(a,aes(x=Date,y=value))+
geom_point()+
coord_cartesian(xlim=c(reactiveList$zoomX1,reactiveList$zoomX2))
ggplotly(g1,source="plot2")
})
}
shinyApp(ui = ui, server = server)
Actually, on my system your code is working fine.
However, you can reduce your code drastically by using plotly's subplot function and it's argument shareX. Please check the following example:
library(ggplot2)
library(plotly)
library(shinydashboard)
library(shinyWidgets)
a <- data.frame(Date = seq.Date(as.Date("2000-01-01"),
as.Date("2000-12-31"),
"day"),
value = rnorm(366))
ui <- dashboardPage(
dashboardHeader(title = "Sample App"),
dashboardSidebar(),
dashboardBody(plotlyOutput("plots", height = "80vh"))
)
server <- function(input, output, session) {
output$plots <- renderPlotly({
g2 <- g1 <- ggplot(a, aes(x = Date, y = value)) +
geom_point()
subplot(ggplotly(g1), ggplotly(g2), nrows = 2, shareX = TRUE)
})
}
shinyApp(ui = ui, server = server)
I have imported the dataset = students for generating the reactive plots but proper plot is not generated .I am using ggplot for plots so could you
please tell me whats wrong in my code.
library(shiny)
library(ggplot2)
ui <- navbarPage("A SHINY APP!! ",
tabPanel("Plots",headerPanel("Different plots of data"),
sidebarLayout(
sidebarPanel(
selectInput("x.col","x.variable",choices=names(students))
),
mainPanel(plotOutput("histPlot")))
)
)
server <- function(input, output) {
plot <- reactive({ ggplot(students,aes(x=input$x.col))
})
output$histPlot <- renderPlot({
plot() + geom_histogram(stat = "count",bins = 30)
})
}
shinyApp(ui = ui, server = server
Try with get() function like the following:
ggplot(students, aes(x = get(input$x.col)))
I want the bar plot to be embedded into application.output of vector d is giving me result I want that to be embedded into shinyapp and later I want to make it interactive too.
library(ggplot2)
driver1 <- read.csv("E:/RMARKDOWN/shiny/driver.csv",header = T)
New_DataSet1<-
data.frame(driver1$ï..Year_AG,driver1$Severity_Desc,driver1$Injury.Type)
New_DataSet1
latest <- New_DataSet1[1:100,]
latest
d <- aggregate(latest$driver1.Injury.Type, by=list(chkID =
latest$driver1.Severity_Desc), FUN=sum)
ui <- dashboardPage(
dashboardHeader(title = "Row layout"),
dashboardSidebar(),
dashboardBody()
)
server <- function(input, output) {
#output$plot <- renderPlot({ barplot(d$x, xlab = d$chkID) })
renderPlot(d$x)
#barplot(d$x, xlab = d$chkID)
# barplot(d$x, names.arg = d$chkID)
}
shinyApp(ui,server)
You can read file first and render it using bar chart as below:
library(plotly)
library(shiny)
ui <- fluidPage(
mainPanel(
plotlyOutput("chart")
)
)
server <- function(input, output, session) {
output$chart <- renderPlotly({
# write code here to read data from csv file
df=read.csv("")
# Set x and y axis and display data in bar chart using plotly
p <- plot_ly( x = iris$Species,
y = iris$Sepal.Length,
name = "Iris data",
type = "bar")
})
}
shinyApp(ui, server)
Screenshot from working demo:
I am building an RShiny-app where I am creating a plot based on a data table which I can edit and another data table which I cannot. I eventually want to save all data points on the plot in a data table which I can display and export.
I have seen many ways to do this using ggplot (ie layer_data, ggplot_build), but no efficient ways when just using plot and lines. My plots will be getting quite complicated so it would be really helpful to find an easy way to do this rather than hardcoding everything in.
A very simple example of my code is below (Note: plots will be getting much more complicated than this. They will be line graphs, but I will just need the y values at each x value marked with a number on the x axis):
x <- data.frame('col_1' = c(1,2,3,4,5), 'col_2' = c(4,5,6,7,8))
y <- data.frame('col_1' = c(5,4,3,6,7), 'col_2' = c(1,2,3,4,5))
#import necessary libraries
library(shiny)
library(DT)
library(shinythemes)
library(rhandsontable)
#ui
ui <- fluidPage(theme = shinytheme("flatly"),
titlePanel("Test"),
sidebarLayout(
sidebarPanel(
#display data
rHandsontableOutput('contents'),
#update plot button
actionButton("go", "Plot Update"),
width=4
),
mainPanel(
tabsetPanel(
#plot
tabPanel("Plot", plotOutput("plot_1")) )
))
)
#server
server <- function(input, output, session) {
#data table
output$table_b <- renderTable(x)
indat <- reactiveValues(data=y)
observe({
if(!is.null(input$contents))
indat$data <- hot_to_r(input$contents)
})
output$contents <- renderRHandsontable({
rhandsontable(indat$data)
})
#save updated data
test <- eventReactive(input$go, {
live_data = hot_to_r(input$contents)
return(live_data)
})
#plot
output$plot_1 <- renderPlot({
plot(x[,1],x[,2],col='red',type = 'l')
lines(test()[,1],x[,2], col='black', type='l')
# need a way to grab data from plot a create a table
})
}
shinyApp(ui, server)
I am trying to create Shiny App which is able to display interactive plot title (dependent on the choosen value for x axis)
Very simple example:
library(shiny)
library(DT)
library(ggplot2)
x <- as.numeric(1:1000000)
y <- as.numeric(1:1000000)
z <- as.numeric(1:1000000)
data <- data.frame(x,y, z)
shinyApp(
ui = fluidPage(selectInput(inputId = "yaxis",
label = "Y-axis",
choices = list("x","y","z"),
selected = c("x")),
dataTableOutput('tableId'),
plotOutput('plot1')),
server = function(input, output) {
output$tableId = renderDataTable({
datatable(data, options = list(pageLength = 10, lengthMenu=c(10,20,30)))
})
output$plot1 = renderPlot({
filtered_data <- data[input$tableId_rows_all, ]
ggplot(data=filtered_data, aes_string(x="x",y=input$yaxis)) + geom_line()
})
}
)
I have tried this code:
ggtitle("Line plot of x vs",input$yaxis)
It was not working, plot has not been displayed, giving me an Error:
Warning: Error in ggtitle: unused argument (input$yaxis)
[IMPORTANT]
using ggtitle(input$yaxis) gives me an interactive title, however i need to build up a sentence (like: Line plot of x vs input$yaxis), in which the reactive argument (input$yaxis) is a part of it!
Thanks for any help!
Cheers
Change:
ggtitle("Line plot of x vs",input$yaxis)
To
ggtitle(paste("Line plot of x vs",input$yaxis))
As the error suggests, you have too many arguments passed to the ggtitle function, paste will create a single character out of your two inputs, with a space in between. You can vary the separation between the two with sep =.