简体   繁体   中英

How can I add a line plot in a BOX plot using secondary y axis but same x axis

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

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(~.))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM