问题描述
我试图重现罗曼在这篇文章中给出的答案: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"
):