0

I am trying to add a line plot to my box plot, on secondary y axis, but i am not able to. what to do? Please help

code for my box plot are:

library(ggplot2)
mydata<-read.csv("boxplot2.csv")
mydata$Class <- factor(mydata$Class,labels = c("1", "2", "3", "4", "5", "6"))
p10 <- ggplot(mydata, aes(x = mydata$Class, y = log(mydata$erosion))) + 
    geom_boxplot()
p10
p10 <- p10 + 
    scale_x_discrete(name = "Mean Annual Precipitation(mm/yr)") +     
    scale_y_continuous(name = "Log Average Erosion Rate(m/My)")
p10 <- ggplot(mydata, aes(x = mydata$Class, y = log(mydata$erosion))) +
    geom_boxplot(varwidth=TRUE)
p10 <- p10 + 
    scale_x_discrete(name = "Mean Annual Precipitation(mm/yr)") +
    scale_y_continuous(name = "Log Average Erosion Rate(m/My)")

I want similar figure, but instead of histograms, i will have box plot

add sample data % Vegetation erosion Class 0 0.43 1 0 0.81 1 2 0.26 1 3 1.05 1 3 0.97 1 12.76 15.97 2 12.84 17.69 2 11.01 14.76 2 13.44 17.94 2 10.76 10.65 2 7.28 67.47 2 23 120.4 3 21 298.63 3 52 21.4 3 9 64.94 3 50 291.88 3 16 493.98 3 11 183.45 3

  • Please provide a reproducible example (with some subset or made-up data). You end up with a boxplot because you do `geom_boxplot()` - what is the question exactly? – Remko Duursma Jul 31 '17 at 01:49
  • I want to add a line plot to my box plot. so the line plot will have secdondary y axis, and same x axis as my box plot – Ashish Mishra Jul 31 '17 at 03:10
  • Idea is to create the same thing like figure above, but instead of histograms, i want box plot, and want the line plot to be as it on secondary y axis – Ashish Mishra Jul 31 '17 at 03:13
  • Post some example data otherwise you will unlikely get any response; or simply search for ggplot2 stacked bar plot. – Remko Duursma Jul 31 '17 at 03:29
  • secondary y-axis is not supported in ggplot by design, see the discussion here: https://stackoverflow.com/a/3101876/7860688. You can still plot a second vertical axis with some tweaks. The process is shown on the same link. I can post that an answer as well if you think that may help. – Sal Jul 31 '17 at 03:56

1 Answers1

0

You just have to specify different aesthetics for the geom_line, something like this:

ggplot(iris,aes(x=Species, y=Sepal.Length, fill=Species)) + 
geom_boxplot() + 
geom_line(aes(x=Species, y=Petal.Length, group=1), stat = "summary", fun.y="mean") +
scale_y_continuous(sec.axis = sec_axis(~.))
Andres
  • 2,413
  • 1
  • 13
  • 18