如何解决具有多个组的ggplot2中的条形宽度
我试图重现罗曼在这篇文章中给出的答案:The same width of the bars in geom_bar(position = "dodge")
但我无法解决我的问题。当条的宽度相同时,组之间的距离太大。使用facet_grid
我的df:
df <- structure(list(discipline = structure(c(2L,3L,2L,4L,6L,7L,8L,3L),.Label = c("","Biogeochemistry","Ecology","Geochemistry","Geography","Management","Microbiology","Oceanography"),class = "factor"),focus = structure(c(34L,55L,40L,47L,54L,57L,19L,31L,25L,23L,52L,13L,20L,16L,26L,27L),"Abiotic measures","Acidification","Biogeochemichal budgets","Biogeochemistry,discharge","Blue Carbon","Chromophoric dissolved organic matter,river plume","Coastal anthromes","Connectivity","Coral reefs","Ecosystem Function","Ecosystem Services","Embryo plants","Fisheries","Food webs","Global change","Governance","Groundwater","Hidrology","Integrative Magamenet","Isotopes","Land-sea interactions","Land-sea interface","Land use","Life history","Life traits","Livelihoods","Microbial community","Modelling water quality","nitrogen fluxes","Nutrients","Parasites","ph,CO2","Planning","Pollutants","Pollution","Primary production","Remote Sensing","Resilience","resilience,self-organization","Restoration","Salinization","Sea level rise","Sediment flux","Sediments","socio land-sea interactions","Species interaction","Submarine ground water","Submarine groundwater","Subsidies","Trace Metals","Trophic interactions","Water quality","Water resources"),n = c(39L,17L,11L,9L,5L,2L)),row.names = c(NA,-20L),class = c("tbl_df","tbl","data.frame"))
首先我尝试使用position = position_dodge2(preserve =“ single”)
ggplot(df,aes(x = (discipline),y = n,fill = reorder(focus,n))) +
geom_bar(position = position_dodge2(width = 0.9,preserve = "single"),stat = "identity") + ylab("N") + theme_classic() + geom_text(aes(label=focus),position = position_dodge2(width = 0.9,angle = 90,hjust = -0.1) + theme(legend.position = "none")
然后我使用了facet_grid
ggplot(df,n))) +
geom_bar(position = "dodge",hjust = -0.1) + theme(legend.position = "none") + facet_grid(scales = "free_x",space = "free_x",switch = "x")
即使条的宽度相等,组之间的距离也太大。 我该怎么办才能解决这个问题?
解决方法
也许尝试一下。看来问题出在position
上。如果为小节定义position_dodge2()
,则可以避免获得大条。这里的代码:
library(ggplot2)
#Code
ggplot(df,aes(x = (discipline),y = n,fill = reorder(focus,n))) +
geom_bar(position = position_dodge2(0.9,preserve = 'single'),stat = "identity") + ylab("N") +
theme_classic() +
geom_text(aes(label=focus),position = position_dodge2(width = 0.9,preserve = "single"),angle = 90,hjust = -0.1) + theme(legend.position = "none") +
facet_grid(scales = "free_x",space = "free_x",switch = "x")
输出:
原始代码会生成此代码(使用position = "dodge"
):
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。