Jack
Jack

Reputation: 857

Is there a way to expand your ggplot figure conditioned on a factor variable?

The figure below shows that the estimate of the UK is "0.4", but it is a bit cut at the end of the graph. One of the solutions is to adjust the hjust option in geom_text. But this is a reproducible example and the original example consists of 30 countries where the estimates of the last country on the x-axis is a bit out of the picture as it is the case here with the UK and the hjust option don't solve the problem. Is there a way to expand more the picture so the estimate "0.4" is clear to the reader?

Here is the plot:

enter image description here

Here is the code:

df %>%
  mutate(label = replace(round(estimate, 2),cntry==1, '')) %>%
  ggplot(aes(estimate, cntry,label=label)) + 
  geom_text(hjust= -2)  + 
  geom_point(mapping=aes(x=estimate, y=cntry), size=2.3, shape=21, fill="black") +
  coord_flip()   

Here is the data:

structure(list(cntry = structure(1:3, .Label = c("FR", "IT", 
"UK"), class = "factor"), term = c("unemp", "unemp", "unemp"), 
    estimate = c(-1.73, 0.20, 0.48
    )), row.names = c(NA, -3L), class = "data.frame")

Upvotes: 1

Views: 25

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545865

You can pass an expansion to your axis scale(s):

df %>%
    mutate(label = replace(round(estimate, 2),cntry==1, '')) %>%
    ggplot(aes(estimate, cntry,label=label)) +
    geom_text(hjust= -2)  +
    geom_point(mapping=aes(x=estimate, y=cntry), size=2.3, shape=21, fill="black") +
    coord_flip() +
    scale_y_discrete(expand = expansion(add = 1))

Upvotes: 1

Related Questions