Place a legend for each facet_wrap grid in ggplot2

前端 未结 4 841
闹比i
闹比i 2020-11-27 04:03

I have this data frame:

        Date Server FileSystem PercentUsed
1  12/1/2011      A          /          60
2   1/2/2012      A       /var          50
3            


        
4条回答
  •  孤城傲影
    2020-11-27 04:19

    I liked @joran's answer and provide a couple of options based off of their code as a starting point. Both options address the issue of mis-aligned facets.

    Legends outside facets

    If you choose a monospaced font for your legend items, you can use str_pad to add padding on the right-hand side of all legend entries, forcing the length of each to be consistent.

    If you're willing to use a monospaced font, this is a quick fix.

    library(ggplot2)
    library(dplyr)
    library(gridExtra)
    library(stringr)
    
    l <- max(nchar(as.character(x$FileSystem)))
    mylevels <- as.character(levels(x$FileSystem))
    mylevels <- str_pad(mylevels, width = l, side = "right", pad = " ")
    x <- mutate(x, FileSystem = factor(str_pad(FileSystem, width = l, side = "right", pad = " "),
                levels = mylevels))
    windowsFonts("Lucida Sans Typewriter" = windowsFont("Lucida Sans Typewriter"))
    xs <- split(x,f = x$Server)
    p1 <- ggplot(xs$A,aes(x = Date,y = PercentUsed,group = 1,colour = FileSystem)) + 
      geom_jitter(size=0.5) + 
      geom_smooth(method="loess", se=T) + 
      facet_wrap(~Server, ncol=1) +
      theme(legend.text = element_text(family = "Lucida Sans Typewriter"))
    
    p2 <- p1 %+% xs$B
    p3 <- p1 %+% xs$C
    
    grid.arrange(p1,p2,p3)
    

    Legends inside facets

    If you don't mind legends inside each facet, you can add extra space to each facet with the "expand" argument inside scale call:

    library(lubridate)
    x <- mutate(x, Date = as.Date(as.character(Date), format = "%m/%d/%Y"))
    xs <- split(x,f = x$Server)
    p1 <- ggplot(xs$A,aes(x = Date,y = PercentUsed,group = 1,colour = FileSystem)) + 
      geom_jitter(size=0.5) + 
      scale_x_date(expand = expansion(add = c(5, 20)),
                   date_labels = "%d-%m-%Y") +
      geom_smooth(method="loess", se=T) + 
      facet_wrap(~Server, ncol=1) +
      theme_bw() +
      theme(legend.position = c(0.9, 0.5))
    
    p2 <- p1 %+% xs$B
    p3 <- p1 %+% xs$C
    
    grid.arrange(p1,p2,p3)
    

提交回复
热议问题