3

Using this data.frame

> df
              var value percent
1 AAAA BBBB CCCCC  -0.5       9
2 FFFF DDDD CCCCC   0.3      13
3 BBBB NNNN DDDDD   0.7      17
4 NNNN MMMM BBBBB  -0.4      25

I want to add the percent and the sign between brackets "like this (9%)" as a second line x axis label.

I did it as below
enter image description here

using this script (following this answer)

my.labels <- c(
  "AAAA BBBB CCCCC\n(9%)",
  "FFFF DDDD CCCCC\n(13%)" ,
  "BBBB NNNN DDDDD\n(17%)",
  "NNNN MMMM BBBBB\n(25%)"
)    

ggplot(df, aes(x = var, y = value))+
  geom_bar(stat ="identity", width = 0.4)+
  scale_x_discrete(labels = my.labels)

It is fine to do this for 4 variables only but if I have many variables, it will be time taking. I think there should be a faster/efficient way to do this for many variables. Any suggestions will be appreciated.

shiny
  • 3,380
  • 9
  • 42
  • 79

1 Answers1

4
my.labels <- paste0(df$var, "\n (", df$percent, "%)")

ggplot(df, aes(x = var, y = value))+
  geom_bar(stat ="identity", width = 0.4)+
  scale_x_discrete(labels = my.labels)

enter image description here

Edit:

The above would not work directly if facet-wrap with scales="free_x" is implemented:

 p <- ggplot(df, aes(x = var, y = value)) +
  geom_bar(stat ="identity", width = 0.4) 

 p + 
   facet_wrap(~var, scales="free_x") +
   scale_x_discrete(labels = my.labels)

enter image description here

To allow the labels to show properly, first add the custom labels back into the data.frame

df$lab <- my.labels

Then using the facet_wrap variable as breaks value for scale_x_discrete function:

 p + 
   facet_wrap(~var, scales="free_x") +
   scale_x_discrete(labels = df$lab, breaks=df$var)

enter image description here

Adam Quek
  • 6,973
  • 1
  • 17
  • 23