Home > Enterprise >  Add coloured underline in the text in bar-chart
Add coloured underline in the text in bar-chart

Time:10-24

Let say I have below bar chart

require(ggplot2)
require(dplyr)

df <- data.frame (Origin = c("Canada", "Canada","USA","USA"),
                  Year = c("2021", "2022","2021","2022"),
                  Sales = c(103, 192, 144, 210),
                  diff = c(89, " ",66," "),
                  perdiff = c(86.4, " ",45.83," "))


df <- df %>% mutate(label= ifelse(diff!=" ",paste0(diff,", ",perdiff,'%'),NA))
ggplot(df, aes(fill=Year, y=Origin, x=Sales))   
  geom_bar(position="dodge", stat="identity") 
  geom_text(aes(label=label, x=200), fontface='bold')  
  scale_x_continuous(breaks=seq(0,200,25)) 
  theme()

While this is fine, I want to add coloured underline under the figures (e.g. 89, 86.4%) which are displayed at the right side of each bar. I should also be able to control the width of such an underline.

Is there any way to achieve this programmatically?

Any pointer will be really helpful

CodePudding user response:

Not sure what you mean by "control the width of such an underline". But one option to add colored underlines to your labels would to add your colored underlines a second geom_text where I use plotmath's underline and phantom to just add the underlines.

library(ggplot2)
library(dplyr)

df <- df %>%
  mutate(label = ifelse(diff != " ", paste0(diff, ", ", perdiff, "%"), NA)) %>%
  mutate(label1 = ifelse(diff != " ", paste0("underline(bold(phantom(\"", diff, ", ", perdiff, "%", "\")))"), NA))

ggplot(df, aes(fill = Year, y = Origin, x = Sales))  
  geom_bar(position = "dodge", stat = "identity")  
  geom_text(aes(label = label, x = 200), fontface = "bold")  
  geom_text(aes(label = label1, x = 200), color = "red", parse = TRUE)  
  scale_x_continuous(breaks = seq(0, 200, 25))
#> Warning: Removed 2 rows containing missing values (geom_text).
#> Removed 2 rows containing missing values (geom_text).

EDIT To add some padding between the label and the line you could increase the vjust in the second geom_text, e.g.:

ggplot(df, aes(fill = Year, y = Origin, x = Sales))  
  geom_bar(position = "dodge", stat = "identity")  
  geom_text(aes(label = label, x = 200), fontface = "bold")  
  geom_text(aes(label = label1, x = 200), color = "red", parse = TRUE, vjust = 1)  
  scale_x_continuous(breaks = seq(0, 200, 25))

enter image description here

  • Related