Ширина полос в ggplot2 со многими группами

Я попытался воспроизвести ответ Романа в этом сообщении: Такая же ширина полос в geom_bar (position = dodge), но я не смог исправить свою проблему. Если столбцы имеют одинаковую ширину, расстояние между группами слишком велико. Та же проблема, когда я использую facet_grid

My df:

df <- structure(list(discipline = structure(c(2L, 3L, 3L, 2L, 2L, 2L,  4L, 6L, 7L, 3L, 4L, 6L, 8L, 8L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("", "Biogeochemistry", "Ecology", "Geochemistry", "Geography", "Management",  "Microbiology", "Oceanography"), class = "factor"), focus = structure(c(34L, 55L, 40L, 47L, 54L, 57L, 47L, 19L, 31L, 25L, 23L, 25L, 47L, 52L,13L, 20L, 23L, 16L, 26L, 27L), .Label = c("", "Abiotic measures", "Acidification", "Biogeochemichal budgets", "Biogeochemistry",  "Biogeochemistry, discharge", "Blue Carbon", "Chromophoric Dissolved organic matter, river plume", "Coastal anthromes", "Connectivity", "Coral reefs", "Ecology", "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", "Management", "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"), class = "factor"), n = c(39L, 17L, 11L, 9L, 6L, 5L, 5L, 4L, 4L, 3L, 3L, 3L, 3L, 3L, 2L, 2L,  2L, 2L, 2L, 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, preserve = "single"), angle = 90, hjust = -0.1) + theme(legend.position = "none") 

введите описание изображения здесь

Затем я использовал facet_grid

ggplot(df, aes(x = (discipline), y = n, fill = reorder(focus, n))) + 
  geom_bar(position = "dodge", 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")

Даже когда ширина полосок одинакова, расстояние между группами слишком велико. Что я могу сделать, чтобы решить эту проблему?


person Matías    schedule 22.10.2020    source источник


Ответы (1)


Может, попробуй это. Похоже, проблема в 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"):

введите описание изображения здесь

person Duck    schedule 22.10.2020
comment
Это моя проблема. Мне нужно такое же расстояние для дисциплин, как на графике 2, но с полосами такой же ширины. Например, на графике 1 расстояние между микробиологией и океанографией слишком велико, я думаю. - person Matías; 22.10.2020