Home > Blockchain >  Adding percentage ratio in the middle of two bars in ggplot
Adding percentage ratio in the middle of two bars in ggplot

Time:09-28

Here is a reproducible example of what I tried;

library(tidyverse)

set.seed(1453)

iris %>% 
group_by(Species) %>% 
summarise(Sepal.Width=mean(Sepal.Width)) %>% 
sample_n(2) %>% 
ggplot(aes(x=Species,y=Sepal.Width,fill=Species)) 
geom_bar(stat='identity',show.legend=F) 
geom_label(aes(label=scales::percent(Sepal.Width[2]/Sepal.Width[1])),show.legend=F)

the current output is looking so;

enter image description here

ggplot repeats the label for each bar. I want just one in the middle of two bars, like this ;

enter image description here

Thanks in advance.

CodePudding user response:

A solution using ggplot2::annotate instead of geom_label:

library(tidyverse)

set.seed(1453)

plot_data <- iris %>% 
  group_by(Species) %>% 
  summarise(Sepal.Width=mean(Sepal.Width)) %>% 
  sample_n(2) 

plot_data %>% 
  ggplot(aes(x=Species,y=Sepal.Width,fill=Species)) 
  geom_bar(stat='identity',show.legend=F) 
  annotate("text", label=scales::percent(plot_data$Sepal.Width[2]/plot_data$Sepal.Width[1]), x= 1.5, y=2)

This returns:

enter image description here

The text can be positioned using the x and y arguments.

CodePudding user response:

I don't know of a great way to put labels between bars on a categorical axis but this is close:

iris %>% 
  group_by(Species) %>% 
  summarise(Sepal.Width=mean(Sepal.Width)) %>% 
  sample_n(2) %>% 
  arrange(Species) %>%
  mutate(
    diff = Sepal.Width/lag(Sepal.Width)
  ) %>%
  ggplot(aes(x=Species,y=Sepal.Width,fill=Species)) 
  geom_bar(stat='identity',show.legend=F) 
  geom_label(aes(label=scales::percent(diff), fill = NA),show.legend=F, hjust = 5.2)
  • Related