How to use a variable to specify column name in ggplot

前端 未结 6 1381
别那么骄傲
别那么骄傲 2020-11-22 03:41

I have a ggplot command

ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )

inside a function. But I would like to be a

6条回答
  •  广开言路
    2020-11-22 04:27

    Using aes_string does fix this problem, but does face an issue when adding error bars geom_errorbar. Below is a simple solution.

    #Identify your variables using the names of your columns indie your dataset
     xaxis   <- "Independent"   
     yaxis   <- "Dependent"
     sd      <- "error"
    
    #Specify error bar range (in 'a-b' not 'a'-'b')
     range   <- c(yaxis, sd)                                #using c(X, y) allows use of quotation marks inside formula
     yerrbar <- aes_string(ymin=paste(range, collapse='-'), 
                           ymax=paste(range, collapse='+'))
    
    
    #Build the plot
      ggplot(data=Dataset, aes_string(x=xaxis, y=yaxis)) +
        geom_errorbar(mapping=yerrbar, width=15, colour="#73777a", size = 0.5) +
        geom_point   (shape=21)
    

    Bonus, you can also add facets to your plot using these lines inside the ggplot:

    facet_grid(formula(paste(Variable1, "~", Variable2)))
    

    This script was modified from this original post: ggplot2 - Error bars using a custom function

提交回复
热议问题