我在r中具有以下数据框,显示了两年中不同社区区域(现场CD)的建筑物数量:
x <- structure(list(numbldgs = c(195, 845, 3621, 3214, 10738, 793,
223, 957, 4248, 3456, 11576, 803), Year = c("2007", "2007", "2007",
"2007", "2007", "2007", "2018", "2018", "2018", "2018", "2018",
"2018"), CD = c("103", "111", "210", "313", "414", "501", "103",
"111", "210", "313", "414", "501")), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))
我正在使用以下代码绘制此数据:
ggplot(x, aes(x=CD, y=numbldgs, fill = Year)) +
geom_bar(stat="identity", width=.9, position = "dodge2") +
labs( x="", y = "Number of buildings")+
theme_classic() +
theme(axis.text.x = element_text(angle=0, vjust=0.5, size=16),
axis.text.y = element_text(angle=0, vjust=0.5, size=16),
legend.text=element_text(size=14), legend.position="bottom",
legend.title = element_text(size=16),
axis.title=element_text(size=12)) +
scale_fill_manual(values=c('#F6D3B5','#D93B0A')) +
scale_y_continuous(labels = function(x) format(x, scientific = FALSE))
哪个返回以下图表:
[我正在尝试在每个社区区域的2018年酒吧上方添加一个标签,该标签显示2007年和2018年值之间的相对增量,将由公式表示:
relative increment = ((value_in_2018 - value_in_2007)/(value_in_2007))*100
除了该值外,还应添加符号“%”-如下所示:
一旦计算百分比/增量值,只需在末尾添加geom_text
(在此示例中,我使用了CD字段:]
ggplot(x, aes(x=CD, y=numbldgs, fill = Year)) +
geom_bar(stat="identity", width=.9, position = "dodge2") +
labs( x="", y = "Number of buildings")+
theme_classic() +
theme(axis.text.x = element_text(angle=0, vjust=0.5, size=16),
axis.text.y = element_text(angle=0, vjust=0.5, size=16),
legend.text=element_text(size=14), legend.position="bottom",
legend.title = element_text(size=16),
axis.title=element_text(size=12)) +
scale_fill_manual(values=c('#F6D3B5','#D93B0A')) +
scale_y_continuous(labels = function(x) format(x, scientific = FALSE))+
geom_text(aes(label=CD))