我正在寻找一种根据因子水平在ggplot2
背景中显示颜色矩形的方法。
这是数据的输入:
structure(list(date = structure(c(6L, 8L, 3L, 4L, 5L, 7L, 1L,
2L), .Label = c("01/05/2012", "10/05/2012", "17/05/2011", "18/05/2011",
"19/05/2011", "20/12/2013", "24/04/2012", "26/12/2013"), class = "factor"),
Polyols = c(122, 5.25, 48.21, 41.59, 84.97, 64.75, 153.97,
49.14), Year = c(2013L, 2013L, 2011L, 2011L, 2011L, 2012L,
2012L, 2012L), Season = structure(c(2L, 2L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = c("Spring", "Winter"), class = "factor"),
Site = structure(c(3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("GAP",
"OPE-ANDRA", "Peyrusse Vieille"), class = "factor"), Typology = structure(c(1L,
1L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Rural", "Urban"), class = "factor")), .Names = c("date",
"Polyols", "Year", "Season", "Site", "Typology"), class = "data.frame", row.names = c(NA,
-8L))
我想要得到的是每个"类型学背后的颜色矩形"如下图所示
我找到This topic但无法找到根据我的情况调整它的方法。
我试过
g <- ggplot(data) +
geom_bar(aes(x= Site, y= Polyols, fill= Season, colour= Season),
show.legend = TRUE,stat="identity",position= position_dodge()) +
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0))
g <- g + geom_rect(data=data, (aes(xmin=Typology, xmax=Typology,
ymin=0,ymax=200,fill=factor(Typology))))
g
有人可以帮忙吗?
答案 0 :(得分:2)
这是一次尝试:
ggplot(dat)+
geom_rect(fill = hue_pal()(4)[as.numeric(dat$Typology)],xmin = -Inf,xmax = Inf,
ymin = -Inf,ymax = Inf, alpha = 0.1, color = "black") +
geom_col(aes(x = Site, y = Polyols, fill = Season))+
coord_cartesian(ylim = c(-50, max(aggregate(Polyols ~ Site, sum, data = dat)[,2])))+
facet_grid(~Typology, scales = "free_x", space="free_x", switch = "x") +
geom_text(aes(x = Site, y = -1, label = Site), angle = 90, hjust = 1) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
panel.spacing = unit(0, "lines"))+
xlab("")
根据背景填充构图,使用geom_rect
填充背景。删除x轴刻度和标签,使用geom_text
注释x
轴。从小平面移除间距。