Reputation: 1967
I've included a lot of sample code because I'm new to Shiny (and still very beginner with R) so I'm not sure where the problem lies.
The first two code blocks are the ui.R and server.R of an app, along with a picture of the output. The problem I'm having is that the "fill" argument in the ggplot command isn't being respected, and I'm getting a mono-color output in the chart, when it should have two different colors in the histogram dependent upon the "id" value in the DF.
The last block of code and image show essentially the same code being run in R-Studio, with the desired effect achieved. You can see in the included output screenshot that there are two overlain histograms colored by the value of the "id" column.
Thanks for any help!
server.R
library(shiny)
library(ggplot2)
id <- sample(0:1, 100, replace=T)
val <- sample(seq(1:25), 100, replace=T)
val2 <- sample(seq(1:10), 100, replace=T)
data <- data.frame(id, val, val2)
# Define a server for the Shiny app
shinyServer(function(input, output) {
# Fill in the spot we created for a plot
output$featurePlot <- renderPlot({
# Render histogram
# Note to readers, the outcome is the same whether the fill command
# is as written, or written as: fill=as.factor(id)
p <- ggplot(data, aes_string(x=input$feature, fill=as.factor(data$id))) +
geom_histogram(alpha=0.5, aes(y=..density..), position='identity', binwidth = input$binSize);
print(p)
})
})
ui.R
library(shiny)
library(ggplot2)
id <- sample(0:1, 100, replace=T);
val <- sample(seq(1:25), 100, replace=T);
val2 <- sample(seq(1:10), 100, replace=T);
data <- data.frame(id, val, val2);
# Define the overall UI
shinyUI(
fluidPage(
titlePanel("why u no color?"),
sidebarLayout(
sidebarPanel(
selectInput("feature", "Feature:",
choices=colnames(data),
selected='val'),
hr(),
helpText("Select a feature to compare"),
sliderInput("binSize",
"Size of Bins",
min = 1,
max = 10,
value = 2)
),
mainPanel(
plotOutput("featurePlot")
)
)
)
)
app output:
# Example Data For help
library(ggplot2)
id <- sample(0:1,100,replace=T)
val <- sample(seq(1:25),100,replace=T)
val2 <-sample(seq(1:10), 100, replace=T)
df <- data.frame(id, val, val2)
ggplot(df, aes(x=val, fill=as.factor(id))) +
geom_histogram(alpha=0.7, aes(y=..density..), position = 'identity', binwidth=1)
Upvotes: 1
Views: 1815
Reputation: 206157
You are setting your fill
in a aes_string
but you're not passing a string, you are trying to pass a vector. Your are mixing up aes()
and aes_string().
Try separating them
p <- ggplot(data, aes_string(x=input$feature)) +
geom_histogram(alpha=0.5, aes(fill=as.factor(id), y=..density..),
position='identity', binwidth = input$binSize);
Upvotes: 2