R Side-by-side grouped boxplot

匆匆过客 提交于 2019-12-11 01:44:23

问题


I have temporal data of gas emissions from two species of plant, both of which have been subjected to the same treatments. With some previous help to get this code together [edit]:

soilflux = read.csv("soil_fluxes.csv") 
library(ggplot2)
soilflux$Treatment <- factor(soilflux$Treatment,levels=c("L-","C","L+"))
soilplot = ggplot(soilflux, aes(factor(Week), Flux, fill=Species, alpha=Treatment)) + stat_boxplot(geom ='errorbar') + geom_boxplot()
soilplot = soilplot + labs(x = "Week", y = "Flux (mg m-2 d-1)") + theme_bw(base_size = 12, base_family = "Helvetica")
soilplot

Producing this which works well but has its flaws.

Whilst it conveys all the information I need it to, despite Google trawls and looking through here I just couldn't get the 'Treatment' part of the legend to show that L- is light and L+ darkest. I've also been told that a monochrome colour scheme is easier to differentiate hence I'm trying to get something like this where the legend is clear.


(source: biomedcentral.com)


回答1:


As a workaround you could create a combined factor from species and treatment and assign the fill colors manually:

library(ggplot2)
library(RColorBrewer)
d <- expand.grid(week = factor(1:4), species = factor(c("Heisteria", "Simarouba")),
                 trt = factor(c("C", "L-", "L+"), levels = c("L-", "C", "L+")))

d <- d[rep(1:24, each = 30), ]
d$flux <- runif(NROW(d))

# Create a combined factor for coding the color
d$spec.trt <- interaction(d$species, d$trt, lex.order = TRUE, sep = " - ")

ggplot(d, aes(x = week, y = flux, fill = spec.trt)) +
   stat_boxplot(geom ='errorbar') + geom_boxplot() +
   scale_fill_manual(values = c(brewer.pal(3, "Greens"), brewer.pal(3, "Reds"))) 



来源:https://stackoverflow.com/questions/26777557/r-side-by-side-grouped-boxplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!