简体   繁体   中英

How to centre single bar position with multiple bars in position_dodge in ggplot2

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"))
    

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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM