1
1
library(shiny )
2
+ library(ggplot2 )
3
+ library(plotly )
2
4
3
5
# Define UI for application that draws a Load-velocity plot
4
6
ui <- fluidPage(
@@ -16,7 +18,7 @@ ui <- fluidPage(
16
18
17
19
# Show a plot of the generated model
18
20
mainPanel(
19
- plotOutput (" lvPlot" )
21
+ plotlyOutput (" lvPlot" )
20
22
)
21
23
)
22
24
)
@@ -36,22 +38,25 @@ server <- function(input, output) {
36
38
data(data.frame (speed = numeric (0 ), charge = numeric (0 )))
37
39
})
38
40
39
- output $ lvPlot <- renderPlot ({
41
+ output $ lvPlot <- renderPlotly ({
40
42
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
+
44
48
if (nrow(plot_data ) > 1 ) {
45
- # Add regression line
46
49
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 ' )
48
51
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 " )
52
55
}
56
+
57
+ ggplotly(p )
53
58
})
54
59
}
55
60
56
61
# Run the application
57
- shinyApp(ui = ui , server = server )
62
+ shinyApp(ui = ui , server = server )
0 commit comments