我有一个使用plotly graphic的Shiny app的简化示例。
# Function, library, data
PlotResponseRate <- function(EntryData)
{
PlotData <- as.data.frame(apply(X = EntryData, MARGIN = 2,
function(x) round(length(which(!is.na(x)))/length(x)*100)))
colnames(PlotData) <- "TheData"
PlotData$TheLabel <- factor(str_wrap(colnames(EntryData), width = 30),
levels = unique(str_wrap(colnames(EntryData), width = 30)))
PlotData$TheLabel <- gsub(pattern = "\n", replacement = "<br>", PlotData$TheLabel)
Graphe <- ggplot(data = PlotData, aes(x = TheLabel, y = TheData)) +
geom_bar(stat = "identity", fill = "red", width = 0.8) +
coord_flip() +
labs(title = "Response rate")
}
library(stringr)
library(ggplot2)
library(plotly)
a <- c(1, 2, 2, 2, NA, 1, 2, 2, 1)
b <- c(2, 1, 2, NA, 2, NA, 1, NA, 1)
df <- data.frame(a, b)
colnames(df) <- c("This Is A Long Answer To A Long Question Label For The First Question",
"This Is A Long Answer To A Long Question Label For The Second Question")
# The Shiny app
Interface <-
{
fluidPage(
sliderInput(inputId = "Num",
label = "Choose the questions",
value = c(1:2), min = 1, max = 2, step = 1),
plotlyOutput("Myplot")
)
}
Serveur <- function(input, output)
{
output$Myplot <- renderPlotly({
Plot1 <- PlotResponseRate(EntryData = df[c(input$Num[1]:input$Num[2])])
ggplotly(Plot1)
})
}
shinyApp(ui = Interface, server = Serveur)
我想要的主要功能是修改绘图的结构。因此,我在renderPlotly
图片中转换后在plotly
中添加了这行代码。
ggplotly(Plot1)
Plot1$x$layout$margin$l <- 180
或者当我添加这一行时,我有一个错误“没有适用于'ggplotly'的方法应用于类”c('double','numeric')的对象“,尽管努力我无法调试。有什么想法吗?
我确切地说它在R命令行中工作正常: Handle long labels in plotly
答案 0 :(得分:0)
根据上面的评论,正确的代码如下。
Serveur <- function(input, output)
{
output$Myplot <- renderPlotly({
Plot1 <- PlotResponseRate(EntryData = df[c(input$Num[1]:input$Num[2])])
Plot1 <- plotly_build(Plot1)
Plot1$x$layout$margin$l <- 180
Plot1 <- ggplotly(Plot1)
})
}