I am trying to create a scatterplot based on a csv I have loaded however when I run the code I either get no plot showing or an error when I include the aes mapping: "Mapping should be created with aes() or aes_()."
Can anyone give me pointers on where I am going wrong?
Code:
library(shiny)
library(ggplot2)
ui <- (fluidPage(
titlePanel("Pig Breeds"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "x",
label = "Pig Breeds:",
choices = c("total_pigs", "female_breeding_herd",
"in_pig_sows", "in_pig_gifts", "other_sows",
"maiden_gilts", "boars_for_service", "other_pigs"),
selected = "total_pigs"),
selectInput(inputId = "y",
label = "Year by year change:",
choices = c(2016, 2017, 2018, "year_on_year_change"),
selected = 2016),
actionButton(inputId = "update", label = "update")
),
mainPanel = (
plotOutput(outputId = "scatterplot")
)
)
)
)
server <- (function(input, output) {
output$scatterplot <- renderPlot({
ggplot(data=(read.csv("eu_pigs.csv")),
aes(x = output$x, y = output$y) +
geom_point())
observeEvent(input$update, {print(as.numeric(input$update))})
}
)
}
)
shinyApp(ui, server)
As the error message says, you’re using aes incorrectly. The function takes column names, not variable references. That is, replace
aes(x = output$x, y = output$y)
by
aes(x = x, y = y)
Or, more likely you want to be able to control the plot from the inputs, so you’d want to use
aes_string(x = input$x, y = input$y)
There are also quite a few stray parentheses and braces in your code. Remove those. Furthermore, mainPanel is a function that you need to call. Your code is instead assigning something to it.
And lastly, you actually need to plot your plot. After all these things are fixed, the relevant code looks like this:
ui <- fluidPage(
titlePanel("Pig Breeds"),
sidebarLayout(
sidebarPanel(…),
mainPanel(
plotOutput(outputId = "scatterplot")
)
)
)
server <- function(input, output) {
output$scatterplot <- renderPlot({
p = ggplot(data = read.csv("eu_pigs.csv")) +
aes_string(x = input$x, y = input$y) +
geom_point()
plot(p)
observeEvent(input$update, print(as.numeric(input$update)))
})
}
If the plot object is the last thing you are executing in the renderPlot function, you can omit plot:
output$scatterplot <- renderPlot({
ggplot(data = read.csv("eu_pigs.csv")) +
aes_string(x = input$x, y = input$y) +
geom_point()
})
Related
The ggplot just shows a vertical line of values that doesn't change when I try changing the x axis selection. The only thing on the x axis is the word "column" when I try to change the x axis, instead of the values of df$column according to what's selected.
df_variable <- df
df_colnames <- colnames(df)
xaxis_input <- selectInput(
inputId = "xaxis",
label = "Feature of Interest",
choices = df_colnames,
selected = df_colnames['default']
)
ui <- fluidPage(
titlePanel("DF"),
xaxis_input,
plotOutput(
outputId = "df_plot",
)
)
server <- function(input, output) {
output$df_plot <- renderPlot({
plot <- ggplot(data = df) +
geom_point(aes(x = input$xaxis, y = some_other_col))
return(plot)
})
}
input$xaxis is a string, so you cannot use it directly inside aes().
Try using aes_string() instead.
Note that some_other_col should also be a string.
server <- function(input, output) {
output$df_plot <- renderPlot({
plot <- ggplot(data = df) +
geom_point(aes_string(x = input$xaxis, y = "some_other_col"))
return(plot)
})
A full working example:
library(shiny)
library(ggplot2)
df <- iris
df_colnames <- colnames(df)
xaxis_input <- selectInput(
inputId = "xaxis",
label = "Feature of Interest",
choices = df_colnames
)
ui <- fluidPage(
titlePanel("DF"),
xaxis_input,
plotOutput(
outputId = "df_plot",
)
)
server <- function(input, output) {
output$df_plot <- renderPlot({
plot <- ggplot(data = df) +
geom_point(aes_string(x = input$xaxis, y = "Sepal.Width"))
return(plot)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Hopefully just a quick question, I have added in a selectInput function into my code and linked this to the server, however whenever I change the "year" within the app the scatterplot doesn't change the plots based on the year.
Am I missing some code?
library(shiny)
library(ggplot2)
pigs <- read.csv("pigs_data.csv")
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Pig Breeding"),
sidebarLayout(
sidebarPanel(
#Allows user to choose a year which changes the distribution of plot points
selectInput(inputId = "year",
label = "Choose a year:",
choices = c(2016, 2017, 2018),
selectize = FALSE
)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("scatterplot")
)
)
)
# Define server logic
server <- function(input, output) {
output$scatterplot <- renderPlot({
input$year
ggplot(pigs,
aes(x = sow_count, y = species, col = species)) +
geom_point() +
facet_grid(. ~year)
})
}
# Run the application
shinyApp(ui = ui, server = server)
EDIT - before trying the observeEvent solution:
Depending on what exactly you want to plot it could be becaose of facet_grid(. ~year) and not facet_grid(. ~input$year).
If facet_grid(. ~input$year) is not what you are looking for, then ...
You can try the observeEvent from the shiny package:
observeEvent(input$year, {
output$scatterplot <- renderPlot({
input$year
ggplot(pigs,
aes(x = sow_count, y = species, col = species)) +
geom_point() +
facet_grid(. ~year)
})
})
Basically whenever the object input$year changes, you render a new plot.
Your example will look like this:
library(shiny)
library(ggplot2)
pigs <- read.csv("pigs_data.csv")
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Pig Breeding"),
sidebarLayout(
sidebarPanel(
#Allows user to choose a year which changes the distribution of plot points
selectInput(inputId = "year",
label = "Choose a year:",
choices = c(2016, 2017, 2018),
selectize = FALSE
)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("scatterplot")
)
)
)
# Define server logic
server <- function(input, output) {
observeEvent(input$year, {
output$scatterplot <- renderPlot({
input$year
ggplot(pigs,
aes(x = sow_count, y = species, col = species)) +
geom_point() +
facet_grid(. ~year)
})
})
}
# Run the application
shinyApp(ui = ui, server = server)
I hope this works for you :)
I think that you need to update your table pigs if it contains the variable year like this:
server <- function(input, output) {
output$scatterplot <- renderPlot({
input$year
ggplot(pigs %>% filter(year %in% input$year),
aes(x = sow_count, y = species, col = species)) +
geom_point() +
facet_grid(. ~year)
})
}
Hope this help.
I am new to R Shiny. Actually i have drawn Stacked Barplot using ggplot in my
R code. I want to draw the same using shiny. Below is my R code:
ggplot(data = df, aes(x = OutPut, y = Group, fill = Group)) +
geom_bar(stat = "identity") +
facet_grid(~ Environment)
In my R code it is giving correct results.But i am trying to draw in shiny. Below is my shiny R code.
ui <- fluidPage(theme = shinytheme("lumen"),
titlePanel("Data Analysis"),
selectInput("variable", "Variable:", c("OutPut", "Member", "Levels")),
mainPanel(plotOutput("plot")))
# Define server function
server <- function(input, output){
x = ggplot(data = df, aes(x = variable.names(), y = Group, fill = Group)) +
geom_bar(stat = "identity") +
facet_grid(~ Environment)
plot(x)
}
# Create Shiny object
shinyApp(ui = ui, server = server)
It is throwing an error,here i have created a dropdown box where all the variables have been stored. So when i select one variable, it should plot the Stacked barplot. Could anyone please help me.
Like it was mentioned in the comments, you need to use the rendering functions and actually assign them to the output to get the outputs you need.
I believe an example of using plots in rshiny would help, since it wouldn't make sense to have it in the comments, here it is:
library(shiny)
library(ggplot2)
ui <- fluidPage(titlePanel("Fast Example with mtcars"),
# inputs
selectInput("x", "Choose x:", choices = names(mtcars), selected = 'mpg'),
selectInput("y", "Choose y:", choices = names(mtcars), selected = 'hp'),
selectInput("fill", "Choose fill:", choices = names(mtcars), selected = 'carb'),
mainPanel(
#outputs
h2("Chosen variables are:"),
h4(textOutput("vars")),
plotOutput("plot")))
server <- function(input, output) {
df <- mtcars
# here's how you would use the rendering functions
# notice that I used aes_string
output$plot <- renderPlot({
ggplot(data=df,
aes_string(x= input$x, y= input$y, fill=input$fill)) +
geom_point()
})
output$vars <- renderText(paste0('x: ', input$x, " , ",
'y: ', input$y, " , ",
'fill: ', input$fill))
}
shinyApp(ui = ui, server = server)
The Rshiny tutorial is pretty helpful, you can take a look at it here https://shiny.rstudio.com/tutorial/
I have tried to plot the graph separately using ggplot (outside the shiny app) and it plots well so I know the problem is not with my ggplot code but with how the inputs in the shiny app are entered into the renderplot({}) section. The inputs are the axes.
Code:
library(ggplot2)
library(shiny)
data1 <- mtcars
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "xaxis",
label = "Choose a Variable for the X-axis of the First Graph",
choices = colnames(data1)
),
selectInput(
inputId = "yaxis",
label = "Choose a Variable for the Y-axis of the First Graph",
choices = colnames(data1)
)
),
mainPanel(
plotOutput(outputId = "scatterplot"))
)
)
server <- function(input, output) {
output$scatterplot <- renderPlot({
req(input$xaxis)
req(input$yaxis)
ggplot(data1, aes(x = input$xaxis, y = input$yaxis))+geom_point()
})}
shinyApp(ui = ui, server = server)
Solution
You are passing a string to your aes, which does not work. You should try
server <- function(input, output) {
output$scatterplot <- renderPlot({
req(input$xaxis)
req(input$yaxis)
gggplot(data1, aes_string(x = paste0("`", input$xaxis, "`"),
y = paste0("`", input$yaxis, "`"))) + geom_point()
})
}
Explanation
aes expects the bare column name like in ggplot(mtcars, aes(am, vs)) + geom_point(). Note that we do not use quotatation marks " for am or vs (i.e. we are passing variable names and not strings). On the other hand input$xaxis returns a string. Thus, you have to use aes_string which is meant for working with strings rather than column names.
Update
Added backtricks to deal with non standard names.
In my shiny app,I want to change the ggplot barChart that I wish to construct. selectinput should allow to change the month (see dataset below) and so my plot should change accordingly.
problem: The isssue is, i am unable to use my reactive function or even just simple input$monthid within ggplot function.
Dataset:
Month Orders
1 Feb 984524
2 Jan 1151303
3 Mar 575000
> dput(b)
structure(list(Month = c("Feb", "Jan", "Mar"), Orders = c(984524L,
1151303L, 575000L)), .Names = c("Month", "Orders"), class = "data.frame", row.names = c(NA,
-3L))
ui.R
library(shiny)
library(shinythemes)
b<-read.csv("b.csv",header=TRUE,sep=",",stringsAsFactors=TRUE)
shinyUI(fluidPage(theme= shinytheme("flatly"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "monthid", label = "Month",choices = b$Month,selected = b$Month[1])),
mainPanel(plotOutput("plot"))
))
)
server.R
library(shiny)
library(shinythemes)
library(ggplot2)
b<-read.csv("b.csv",header=TRUE,sep=",",stringsAsFactors=TRUE)
shinyServer(function(input, output) {
#making a reactive object
m<-reactive ({
as.character(input$monthid)
})
output$plot<- renderPlot({
#probably I am making a subset error in x inside aes parameter
ggplot(data = b, aes(x = b[,m()] ,y = b$Orders)) + geom_bar(stat="identity")
})
})
Here's a minimal working example you can copy and paste right in your session to run, but a bar chart with a single bar doesn't really make a lot of sense (and looks ugly if you ask me):
library(shiny)
shinyApp(
ui = fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "monthid",
label = "Month",
choices = b$Month,
selected = b$Month[1]
)
),
mainPanel(plotOutput("plot"))
)
),
server = function(input, output) {
DF <- reactive({
b[b$Month == input$monthid, , drop = FALSE]
})
output$plot <- renderPlot({
ggplot(DF(), aes(x = Month, y = Orders)) +
geom_bar(stat = "identity")
})
}
)
It looks somewhat like this:
Since that doesn't look nice IMO, you could do something with highlighting the currently selected bar, for example:
b$highlight <- factor("Not Selected", levels = c("Not selected", "Selected"))
shinyApp(
ui = fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "monthid",
label = "Month",
choices = b$Month,
selected = b$Month[1]
)
),
mainPanel(plotOutput("plot"))
)
),
server = function(input, output) {
DF <- reactive({
b[b$Month == input$monthid, "highlight"] <- "Selected"
b
})
output$plot <- renderPlot({
ggplot(DF(), aes(x = Month, y = Orders, fill = highlight)) +
geom_bar(stat = "identity")
})
}
)
This would look as follows: