How to adjust the legend of a graphic generated in Shiny

Could you help me adjust the legend of my graph?. I will insert an image showing how I would like it to look. I adjusted the insert of legend, however when I go to run the shiny, it doesn't show. I would like the legend to be under the graph.

Code below:


df1 <- structure(
  list(date1= c("2021-06-28","2021-06-28","2021-06-28","2021-06-28"),
       date2 = c("2021-06-30","2021-06-30","2021-07-01","2021-07-02"),
       Category = c("FDE","ABC","FDE","ABC"),
       Week= c("Wednesday","Wednesday","Friday","Friday"),
       DR1 = c(4,1,6,1),
       DR01 = c(4,1,4,4), DR02= c(4,2,6,0),DR03= c(9,5,4,0),
       DR04 = c(5,4,3,5),DR05 = c(5,4,5,0),
       DR06 = c(2,4,3,5),DR07 = c(2,5,4,0),
       DR08 = c(3,4,5,0),DR09 = c(2,3,4,0)),
  class = "data.frame", row.names = c(NA, -4L))

ui <- fluidPage(
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                                   tabPanel("", plotOutput("graph",width = "100%", height = "600")

server <- function(input, output,session) {
  output$date <- renderUI({
    all_dates <- seq(as.Date('2021-01-01'), as.Date('2021-01-15'), by = "day")
    disabled <- as.Date(setdiff(all_dates, as.Date(data()$date2)), origin = "1970-01-01")
    entrydate<- dateInput(input = "Date2", 
                          label = h4("Choose"),
                          min = min(data()$date2),
                          max = max(data()$date2),
                          format = "dd-mm-yyyy",
                          datesdisabled = disabled)
    entrydate$children[[2]]$attribs$placeholder <- "No selected date"
  output$mycode <- renderUI({
    df1 <- data()
    df5 <- df1[as.Date(df1$date2) %in% input$Date2,]
    selectInput("code", label = h4("Category"),choices=c("No code selected" = "", sort(unique(df5$Category))))
  output$graph <- renderPlot({
    df1 <- data()
    legend("bottomright",inset=c(-0,-0), legend= 3,title="The number is é:",title.col = "black", cex = 1.2)})

shinyApp(ui = ui, server = server) 


enter image description here

Have you tried running it outside of shiny ?
I don't think you would need to do anything different in shiny than out of it in terms of the base R plotting code. It would make your reprex better for it to be minimal, i.e. not include shiny code without a specific need for shiny code.

plotting legends on the inside is the default, you are correct to try to manual shift this with inset (though you have shifted it by zero...). I think you need to use legends xpd param set to TRUE to move the clipping outside of the plot region to the wider figure so that the legend will be seen. You may or may not also have to alter the plot's margin size depending on the circumstances.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.