Function to build double y axis graph in ggplot2

后端 未结 3 991

I am testing a function to build a double y axis graph in ggplot2. It works but I can\'t get some elements from the input graphics. I have built these two graphs with two data f

3条回答
  •  遥遥无期
    2021-02-20 01:34

    Another smarter approach with sec_axis adapted from here.

    Advantage:

    1. Native secondary axis, only one ggplot object is created.
    2. No hacks involving explicitly tweaking axis objects.

    Disadvantage: Limits of the two axes must be defined beforehand.

    Refer to sec_axis documentation and the blog post (in Japanese) for more information.

    # You must define limits first
    
    AXIS1_MIN = 0
    AXIS1_MAX = max(Base1$value)
    AXIS2_MIN = min(Base2$value)
    AXIS2_MAX = max(Base2$value)
    
    scale_to_value1 <- function(values) rescale(values, to = c(AXIS1_MIN, AXIS1_MAX))
    scale_to_value2 <- function(values) rescale(values, to = c(AXIS2_MIN, AXIS2_MAX))
    
    ggplot() +
      geom_bar(aes(x = Month, y = value, fill = variable), data = Base1, stat="identity",colour="black",size=1) +
      geom_line(aes(x = Month, y = scale_to_value1(value),color = variable, group = variable), data = Base2, size=1.3) +
      scale_y_continuous(labels = comma,breaks=pretty_breaks(n=7),
                         limits=c(AXIS1_MIN, AXIS1_MAX),
                         sec.axis = sec_axis( ~ scale_to_value2(.), name = "value2")) +
      scale_color_manual(name = "variable", 
                        label = c("Index1", "Index2"), 
                        values = c("Index1" = "red", "Index2" = "green")) +
      scale_fill_manual(name = "variable", 
                        label = "Power",
                        values = "#FF6C91") +
      theme(axis.text.x=element_text(angle=90,colour="grey20",face="bold",size=12),
            axis.text.y=element_text(colour="grey20",face="bold",hjust=1,vjust=0.8,size=15),
            axis.title.x=element_text(colour="grey20",face="bold",size=16),
            axis.title.y=element_text(colour="grey20",face="bold",size=16)) +
      xlab('Month')+ylab('')+ ggtitle("My graph") +
      theme(plot.title = element_text(lineheight=3, face="bold", color="black",size=24)) +
      theme(legend.text=element_text(size=14),
            legend.title=element_text(size=14))
    

提交回复
热议问题