Skip to content

Commit a3458bf

Browse files
authored
Merge pull request #6 from Boudry-Felix/interactive-plot
Interactive plot (plotly) + equation + title.
2 parents 50dc83c + 2ac55ac commit a3458bf

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

app.R

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
library(shiny)
2+
library(ggplot2)
3+
library(plotly)
24

35
# Define UI for application that draws a Load-velocity plot
46
ui <- fluidPage(
@@ -16,7 +18,7 @@ ui <- fluidPage(
1618

1719
# Show a plot of the generated model
1820
mainPanel(
19-
plotOutput("lvPlot")
21+
plotlyOutput("lvPlot")
2022
)
2123
)
2224
)
@@ -36,22 +38,25 @@ server <- function(input, output) {
3638
data(data.frame(speed = numeric(0), charge = numeric(0)))
3739
})
3840

39-
output$lvPlot <- renderPlot({
41+
output$lvPlot <- renderPlotly({
4042
plot_data <- data()
41-
plot(plot_data$charge, plot_data$speed,
42-
xlab = "Charge (kg)", ylab = "Speed (m/s)",
43-
main = "Load-velocity Model", pch = 19)
43+
p <- ggplot(plot_data, aes(x = charge, y = speed)) +
44+
geom_point() +
45+
labs(x = "Charge (kg)", y = "Speed (m/s)", title = "Load-velocity Model") +
46+
theme(plot.title = element_text(hjust = 0.5)) # Center the plot title
47+
4448
if(nrow(plot_data) > 1) {
45-
# Add regression line
4649
fit <- lm(speed ~ charge, data = plot_data)
47-
abline(fit, col = "blue")
50+
p <- p + geom_smooth(method = "lm", col = "blue", se = FALSE, formula = 'y ~ x')
4851

49-
# Optionally, add the regression equation to the plot
50-
eq <- paste0("y = ", round(coef(fit)[1], 2), " + ", round(coef(fit)[2], 2), "x")
51-
legend("topleft", legend = eq, bty = "n")
52+
# Add the regression equation to the plot
53+
eq <- paste0("y = ", round(coef(fit)[1], 4), " + ", round(coef(fit)[2], 4), "x")
54+
p <- p + annotate("text", x = mean(plot_data$charge), y = max(plot_data$speed), label = eq, size = 4, color = "blue")
5255
}
56+
57+
ggplotly(p)
5358
})
5459
}
5560

5661
# Run the application
57-
shinyApp(ui = ui, server = server)
62+
shinyApp(ui = ui, server = server)

0 commit comments

Comments
 (0)