Showing different axis labels using ggplot2 with facet_wrap

前端 未结 3 907
粉色の甜心
粉色の甜心 2020-12-08 09:55

I have a time series with different variables and different units that I want to display on the same plot.

ggplot does not support multiple axis (as explained here),

3条回答
  •  无人及你
    2020-12-08 10:39

    Super late entry, but just solved this for myself...A super simple hack that lets you retain all strip.text is to just enter a bunch of spaces in ylab(" Voltage (V) Current (A)\n") in order to put the title across both plots. You can left-justify using axis.title.y = element_text(hjust = 0.25) to align everything well.

    library(tidyverse)
    library(reshape2)
    x <- seq(0, 10, by = 0.1)
    y1 <- sin(x)
    y2 <- sin(x + pi / 4)
    y3 <- cos(x)
    
    my.df <-
        data.frame(
            time = x,
            currentA = y1,
            currentB = y2,
            voltage = y3
        )
    my.df <- melt(my.df, id.vars = "time")
    my.df$Unit <- as.factor(rep(c("A", "A", "V"), each = length(x)))
    
    ggplot(my.df, aes(x = time, y = value)) + 
        geom_line(aes(color = variable)) + 
        facet_wrap( ~Unit, scales = "free_y", nrow = 2) +
        ylab("             Voltage (V)                                          Current (A)\n") +
        theme(
            axis.title.y = element_text(hjust = 0.25)
        )
    ggsave("Volts_Amps.png",
           height = 6,
           width = 8,
           units = "in",
           dpi = 600)
    

提交回复
热议问题