我已经包含了很多示例代码,因为我是Shiny的新手(并且仍然是R的初学者)所以我不确定问题出在哪里。
前两个代码块是应用程序的ui.R和server.R,以及输出图片。 我遇到的问题是ggplot命令中的“fill”参数没有得到遵守,我在图表中得到单色输出,当它在柱状图中应该有两种不同的颜色时,取决于DF中的“id”值。
最后一段代码和图像显示了在R-Studio中运行的相同代码,实现了所需的效果。您可以在包含的输出屏幕截图中看到,有两个覆盖的直方图由“id”列的值着色。
感谢您的帮助!
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输出:
# 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)
答案 0 :(得分:2)
您要将fill
设置为aes_string
,但是您没有传递字符串,而是尝试传递矢量。您正在混淆aes()
和aes_string().
尝试将它们分开
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);