I have the following geom_bar dodged plot and think the single bars for Ages 8, 17, 26 and 27 would look better centralized rather than off to the left. I am not sure what to add to the script to achieve this. Any assistance would be greatly appreciated.
This is the script:
ggplot(data = combo1, aes(x = Age_Year, fill = Tactic))
geom_bar(position = position_dodge(preserve = 'single'))
theme_classic()
labs(x = "Age (years)", y = "Counts of Fish", show.legend = FALSE)
theme(legend.position = "none")
scale_fill_manual("legend", values = c("Migr" = "skyblue", "OcRes" = "pale green", "EstRes" = "pink"))
CodePudding user response:
OP, use position_dodge2(preserve="single")
in place of position_dodge(preserve="single")
. For some reason, centering bars/columns doesn't quite work correctly with position_dodge()
, but it does with position_dodge2()
. Note the slight difference in spacing you get when you switch the position function, but should overall be the fix to your problem.
Reproducible Example for OP's question
library(ggplot2)
set.seed(8675309)
df <- data.frame(
x=c("A", "A", "A", "B", "C", "C"),
grouping_var = c("Left", "Middle", "Right", "Middle", "Left", "Right"),
values = sample(1:100, 6))
Basic plot with position_dodge()
:
ggplot(df, aes(x=x, y=values, fill=grouping_var))
geom_col(position=position_dodge(preserve = "single"))
theme_classic()
When you use position_dodge2()
:
ggplot(df, aes(x=x, y=values, fill=grouping_var))
geom_col(position=position_dodge2(preserve = "single"))
theme_classic()