Home > Software design >  R ggplot - How to increase the space between 0 and y values
R ggplot - How to increase the space between 0 and y values

Time:02-23

I'm adding data labels to my visuals and whenever I have values close to zero my data labels are cut off in proximity of the y axis. See an example in the image below. Is there a way to increase the space between the 0 value and the Y axis values?

Code for the example below:

AgencyComposition <- data_frame(
                      Agency = c("Unassigned", "SOFTEL", "HHS", "BESTLIFE")
                      Users = c(1, 40, 3, 2)
)

AgencyComposition

And here's the visual:

V_agencycomposition <- AgencyComposition %>% 
                            ggplot(
                              aes(
                                x = Users, 
                                y = Agency
                              )
                            )  
                        geom_col(
                            aes(
                              fill = "Users"
                            ), 
                            alpha = .8
                          )  
                        labs(
                          x = "Number of users",
                          y = "Agency",
                          color = "User count"
                        )  
                        geom_label(
                            aes(label = Users), 
                            hjust = 1.2
                        )  
                        theme(legend.position = "bottom")

V_agencycomposition

Thanks in advance!

Example of visual with labels

CodePudding user response:

You can use expand inside scale_x_continuous. Here, I've used c(0.1, 0), but if you want a larger gap on the left hand side you can make the 0.1 as large as you like.

AgencyComposition %>%

ggplot(
  aes(
    x = Users, 
    y = Agency
  )
)  
  geom_col(
    aes(
      fill = "Users"
    ), 
    alpha = .8
  )  
  labs(
    x = "Number of users",
    y = "Agency",
    color = "User count"
  )  
  geom_label(
    aes(label = Users), 
    hjust = 1.2
  )  
  scale_x_continuous(
    expand = c(0.1, 0)
  )  
  theme(legend.position = "bottom")

V_agencycomposition

enter image description here

  • Related