Using shiny input values in a ggplot aes - r

I'm trying to implement these 3 lines of code, which is my desired output, in Shiny.
install.packages("ggalt")
library(ggalt)
health <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area)) # did something for graph
ggplot(health, aes(x=pct_2013, xend=pct_2014, y=Area))+
geom_dumbbell()
In Shiny, I want a user to be able to choose starting and ending points of a lollipop graph. I also want a user to be able to choose a categorical variable (among many categorical variables -- even though for now, the example data only has one categorical variable) that would show up on the y-axis. Below is what I worked on so far, literally replacing all variables to input variables (so I think it should work but it doesn't..)
ui<-pageWithSidebar(
headerPanel('Lollipop Chart'),
sidebarPanel(
selectInput('xcol', 'X Variable', names(health), selected=names(health)[1]),
selectInput('val1', 'Starting Value', names(health), selected=names(health)[3]),
selectInput('val2', 'Ending Value', names(health), selected=names(health)[2]) ),
mainPanel(
plotOutput('plot1')
)
)
server<-function(input, output, session) {
health < read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area)) # did something for graph
selectedData <- reactive({
health[, c(input$xcol, input$val1, input$val2)]
})
output$plot1 <- renderPlot({
ggplot(selectedData(), aes(x=input$val1, xend=input$val2, y=input$xcol))+
geom_dumbbell()
})
}
shinyApp(ui, server)
Could anyone help why am I not getting the desired output? :(

The desired plot doesn't show up because you are calling ggplot in a different way. In your shiny app the selected column names are strings:
ggplot(health, aes(x='pct_2013', xend='pct_2014', y='Area'))+
geom_dumbbell()
Replace the aes with aes_string and it will work.
ggplot(health, aes_string(x='pct_2013', xend='pct_2014', y='Area'))+
geom_dumbbell()

Related

shiny interactive plot outputs the real coordinates on the data?

My app that i built outputs the coordinates of the clicked point but my objective is to output the coordinates of the plotted point and that is by printing out the real correspendent coordinates existing on the x axis .This is the first part of the post i want to resolve, then if it is done then we will deal with the fact that my app deals with an x axis of a date nature then we will plot another plot, instaed of the actual, which in fact based on filtering the data based on that date .But now i want to get using the code below the abscisse which is written on the x axis and not that numerical delivered but R shiny:
library(ggplot2)
library(shiny)
library(shiny)
df<-data.frame("pr"=c("a","n","z","o"),"value"=c(5,1,13,9))
ui <- basicPage(
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info")
)
server <- function(input, output) {
output$plot1 <- renderPlot({
plot(as,factor(df$pr ), df$value)
})
output$info <- renderText({
paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
})
}
shinyApp(ui, server)
By the way who can disply the points in form of points and not in form of bars or bold lines like in my example so please do it .i will be thankful.

the ggplot won't display in the shiny [duplicate]

I'm trying to implement these 3 lines of code, which is my desired output, in Shiny.
install.packages("ggalt")
library(ggalt)
health <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area)) # did something for graph
ggplot(health, aes(x=pct_2013, xend=pct_2014, y=Area))+
geom_dumbbell()
In Shiny, I want a user to be able to choose starting and ending points of a lollipop graph. I also want a user to be able to choose a categorical variable (among many categorical variables -- even though for now, the example data only has one categorical variable) that would show up on the y-axis. Below is what I worked on so far, literally replacing all variables to input variables (so I think it should work but it doesn't..)
ui<-pageWithSidebar(
headerPanel('Lollipop Chart'),
sidebarPanel(
selectInput('xcol', 'X Variable', names(health), selected=names(health)[1]),
selectInput('val1', 'Starting Value', names(health), selected=names(health)[3]),
selectInput('val2', 'Ending Value', names(health), selected=names(health)[2]) ),
mainPanel(
plotOutput('plot1')
)
)
server<-function(input, output, session) {
health < read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area)) # did something for graph
selectedData <- reactive({
health[, c(input$xcol, input$val1, input$val2)]
})
output$plot1 <- renderPlot({
ggplot(selectedData(), aes(x=input$val1, xend=input$val2, y=input$xcol))+
geom_dumbbell()
})
}
shinyApp(ui, server)
Could anyone help why am I not getting the desired output? :(
The desired plot doesn't show up because you are calling ggplot in a different way. In your shiny app the selected column names are strings:
ggplot(health, aes(x='pct_2013', xend='pct_2014', y='Area'))+
geom_dumbbell()
Replace the aes with aes_string and it will work.
ggplot(health, aes_string(x='pct_2013', xend='pct_2014', y='Area'))+
geom_dumbbell()

R shiny, cannot set column names with Shiny reactive variable for ggplot

I recently start building shiny app but I got stuck. Please help me.Thank you in advance
I am trying to create a bar chart to show the count for different type of cash and different term. This part, the code went well.
And I also want to create the box plot to show the numeric summary for different variables selected by the user. I created a selectInput called "metric" and then create a reactive called "metric1" in server.R. and then use "metric1" as the variables I selected to create box plot in server.R.
But it keep saying "cannot find the function "metric1". I don't know why it regards "metric1" as a function? it should be a vector-name of the variable selected by the user.
And if I use input$metric in ggplot to create box plot directly, it still say Error: " object 'input' not found". Why cannot find input? I have paste the code below. It is not a long code. And please help me!
library(shiny)
library(ggplot2)
cash <- read.csv("cash 042014-032015.csv")
cash$TERM <- as.numeric(cash$TERM)
shinyServer(function(input, output) {
dataset <- reactive({cash[cash$mapped_name %in% (input$model),]})
metric1 <- reactive({input$metric})
output$caption <- renderText({
input$model
})
output$countPlot <- renderPlot({
p <- ggplot(dataset(), aes(Incentive.Type, fill=factor(Incentive.Type))) + geom_bar()+ facet_grid(~TERM, margins=TRUE)+theme(axis.text.x = element_blank(),axis.ticks=element_blank(),legend.text = element_text(size=20))+guides(fill=guide_legend(title="Incentive Type"),title.theme=element_text(size=30))+scale_x_discrete(limits=c("Standard","Standard+Captive","Standard+Customer","Standard+Captive+Customer","Special","Special+Captive","Special+Customer","Special+Captive+Customer"))
print(p)
})
output$summaryPlot <- renderPlot({
p <- ggplot(dataset(),aes(factor(Incentive.Type), metric1()))+geom_boxplot()
print(p)
})
})
Here is the ui.R
library(shiny)
library(ggplot2)
dataset <- cash
shinyUI(
fluidPage(
# Give the page a title
titlePanel("Incentives by Model"),
# Generate a row with a sidebar
sidebarPanel(
checkboxGroupInput("model", "Select Models:",
choices=c("370Z","Altima","Armada","Crew","Cube","Frontier","GTR","Juke","Leaf",
"Maxima","Murano","NV","Other","Pathfinder","Quest","Rogue","Sentra","Titan","Versa","Xterra"),selected="Altima"),
selectInput("metric","Please select an option below:", choices=c("Dealer Commission Amount"="DLR_COMM_AMT", "Total Monthly Payment"="TOT_MO_PMT","Original Loan Amount"="ORIG_LN_AMT", "Rate"="RATE"),
selected="DLR_COMM_AMT"),
width=2
),
mainPanel(
h3(textOutput("caption", container=span)),
plotOutput("countPlot"),
plotOutput("summaryPlot")
)
))
Try changing metric1() in the second ggplot call to metric1. As in:
p <- ggplot(dataset(),aes(factor(Incentive.Type), metric1))+geom_boxplot()
Actually I think you will have to use something like:
p <- ggplot(dataset(),aes_string(factor("Incentive.Type"), "metric1"))+geom_boxplot()
In order to get it to see the value of your variable metric1 and properly interpret the use of string variables inside of ggplot.

Many error signs when running ggplot in render plot (shiny in general)

Took very basic shiny scripts and were able to play around the generic data sets. When I tried to put in my own and run ggplot, I've come across several errors. Most recent is what appears in my main panel of shiny app and console in Rstudio
...
"ggplot2 doesn't know how to deal with data of class reactive"
...
In general, I stripped down my ggplot to the most basic elements and still not sure from where ggplot is calling data while in shiny. I am guessing the reactive function, but honestly, I am lost.
Below are scripts
_____ui.R________
shinyUI(pageWithSidebar(
headerPanel('Mock Risk Scorecard'),
sidebarPanel(
selectInput('xcol', 'X Axis', names(RandomRiskCard)),
selectInput('ycol', 'Y Axis', names(RandomRiskCard),
selected=names(RandomRiskCard)[[2]]),
min = 1, max = 9),
mainPanel(
plotOutput('plot1')
)
)
)
_____server.R____
palette(c("#E41A1C", "#377EB8"))
shinyServer(function(input, output, session) {
# Combine the selected variables into a new data frame
selectedData <- reactive({
RandomRiskCard[, c(RandomRiskCard$xcol, RandomRiskCard$ycol)]
})
output$plot1 <- renderPlot({
p <- ggplot(selectedData, aes(x = RandomRiskCard$xcol, y = RandomRiskCard$ycol))
p <- p + geom_point()
})
})
I also loaded up my data and Run Shiny in different script windows as follow
install.packages("shiny")
library(shiny)
library(ggplot2)
runApp("U:/App-1")
as well as
RandomRiskCard = read.csv("U:/App-1/RandomRiskCard.csv")
I am eventually hoping to incorporate factor function and annotate with colors like I had done with my original ggplot. If it wasn't already obvious I am a newbie at this, but shiny has me completely twisted.
Reactive expressions should be called in the same way as parameter-less functions, with following parentheses: ggplot(selectedData(),...
xcol and ycol should be obtained via input:
p <- ggplot(selectedData(), aes(x = input$xcol, y = input$ycol)) in output$plot, and
RandomRiskCard[, c(input$xcol, input$ycol)] in selectedData

How to Order ggplot2 x-axis dates chronologically when in mm-yyyy format?

I'm designing an R program to output different graphs of any csv file input. I am using Rstudio Shiny and ggplot2 to develop the program.
My problem involves ordering dates chronologically rather than alphabetically (which is the default apparently). Let's use this code as an example (my code is a bit different, but this is code from someone who helped me earlier):
related posts:
Unable to change the graph form of my ggplot rshiny program, help me find the bug?
Sorting months in R
How do you order a nominale variable. e.g month in R?
Boxplot with ggplot2 in R - returns by month
server.R
library(shiny)
library(datasets)
library(ggplot2)
X <- read.csv(file.choose())
# Define server logic required to summarize and view the selected dataset
shinyServer(function(input, output) {
output$opt.x <- renderUI({
selectInput("xcolumn", "X column to Plot",
names(Y())
)
})
output$opt.y <- renderUI({
selectInput("ycolumn", "Y Column",
names(Y()))
})
# Generate a summary of the dataset
output$summary <- renderPrint({
dataset <- X
summary(dataset)
})
# Show the first "n" observations
output$view <- renderTable({
head(X, n = input$obs)
})
createPlot <- function(df, colx, coly) {
p <- ggplot(data=df, aes(x=df[,colx],y=df[,coly]), environment = environment()) #+ geom_line(aes(x=df[,colx],y=df[,coly], group=colx))
p <- p + geom_line(aes(group=colx))
p <- p + xlab(names(df)[colx]) + ylab(names(df)[coly])
}
Y <- reactive({
X
})
# create a basic plot
output$plotBasic <- reactivePlot(function() {
df <- Y()
print(createPlot(df, colx=input$xcolumn, coly=input$ycolumn))
})
})
ui.R
library(shiny)
# Define UI for dataset viewer application
shinyUI(pageWithSidebar(
# Application title
headerPanel("My app!"),
# Sidebar with controls to select a dataset and specify the number
# of observations to view
sidebarPanel(
numericInput("obs", "Number of observations to view:", 13),
uiOutput("opt.x"), #dynamic UI
uiOutput("opt.y") #value comes from Server.R
),
# Show a summary of the dataset and an HTML table with the requested
# number of observations
mainPanel(
tabsetPanel(
tabPanel("Table", tableOutput("view")),
tabPanel("BasicGraph", plotOutput("plotBasic"))
)
)
))
This can be taken care of easily with factor or as.Date functions if you started with a list that you knew of, but here I am taking in input (can assume the format is mm-yyyy) and I do not know how to set the column of x variable data to a variable. This is because the user can choose any column in the imported data as the X column.

Resources