R shiny:使用通过 ui 获得的字符串在绘图标题中表达方程式
R shiny: expressing an equation in a plot title using a string obtained by ui
我写了下面的r代码:
remove(list = ls())
library(shiny)
library(ggplot2)
ui <- pageWithSidebar(
headerPanel('Plot a function'),
sidebarPanel(
textInput("func", "Function to plot:", value = "x"),
numericInput("xMin", "Set the minimum of x: ", value = 0),
numericInput("xMax", "Set the maximum of x: ", value = 10),
submitButton("Plot")
),
mainPanel(plotOutput("plot"))
)
server <- function(input, output) {
output$plot <- renderPlot({
x <- seq(input$xMin, input$xMax, 0.01)
f <- function(x) {
eval(parse(text = input$func))
}
y <- f(x)
df <- data.frame(x, y)
theme_set(theme_bw(base_size = 12))
figure <- ggplot(df, aes(x, y)) +
geom_line() +
labs(x = "x",
y = "y",
title = parse(text = input$func)) +
theme(plot.margin = unit(c(.6, .6, .6, .6), "cm"),
plot.title = element_text(hjust = 0.5))
plot(figure)
filename <- "plotFunction.jpeg"
ggsave(filename,
width = 6,
height = 4,
dpi = 200)
})
}
shinyApp(ui = ui, server = server)
当用户输入x^2 - 2
指定函数时,我得到如下输出:
Output of the code
我想让剧情标题以y =
开头(这样整个标题会变成y = x^2 - 2
,x^2
渲染正确),但是我一直做不到所以。例如,如果我将用户输入字符串与 y =
连接起来,标题将变为 (= y, x^2 - 2)
(尽管 x^2
已正确呈现)。
你可以这样做:
labs(title = parse(text=paste0("y == ", input$func)))
我写了下面的r代码:
remove(list = ls())
library(shiny)
library(ggplot2)
ui <- pageWithSidebar(
headerPanel('Plot a function'),
sidebarPanel(
textInput("func", "Function to plot:", value = "x"),
numericInput("xMin", "Set the minimum of x: ", value = 0),
numericInput("xMax", "Set the maximum of x: ", value = 10),
submitButton("Plot")
),
mainPanel(plotOutput("plot"))
)
server <- function(input, output) {
output$plot <- renderPlot({
x <- seq(input$xMin, input$xMax, 0.01)
f <- function(x) {
eval(parse(text = input$func))
}
y <- f(x)
df <- data.frame(x, y)
theme_set(theme_bw(base_size = 12))
figure <- ggplot(df, aes(x, y)) +
geom_line() +
labs(x = "x",
y = "y",
title = parse(text = input$func)) +
theme(plot.margin = unit(c(.6, .6, .6, .6), "cm"),
plot.title = element_text(hjust = 0.5))
plot(figure)
filename <- "plotFunction.jpeg"
ggsave(filename,
width = 6,
height = 4,
dpi = 200)
})
}
shinyApp(ui = ui, server = server)
当用户输入x^2 - 2
指定函数时,我得到如下输出:
Output of the code
我想让剧情标题以y =
开头(这样整个标题会变成y = x^2 - 2
,x^2
渲染正确),但是我一直做不到所以。例如,如果我将用户输入字符串与 y =
连接起来,标题将变为 (= y, x^2 - 2)
(尽管 x^2
已正确呈现)。
你可以这样做:
labs(title = parse(text=paste0("y == ", input$func)))