Search code examples
rggplot2plotlyr-highcharter

labels misplaced with geom_grid


In the plots below, I want the labels to be at the center. However, they are misplaced. How to fix it? Also: is the same plot possible to reproduce with highcharter? Below is a dummy data:

library(tidyverse)
library(plotly)
df = tibble(category = c('A', 'A', 'B', 'B', 'C', 'C', 'A', 'A', 'B', 'B', 'C', 'C'),
           targeting = c('Automatic', 'Manual','Automatic', 'Manual','Automatic', 'Manual', 'Automatic', 'Manual','Automatic', 'Manual','Automatic', 'Manual'),
           spend_percentage = c(
                 35.3, 64.7, 12.9, 87.1, 73.9, 26.1, 73.3, 26.7, 50.4, 49.6, 35, 65),
           type = c('Unoptimized', 'Unoptimized', 'Unoptimized','Unoptimized', 'Unoptimized', 'Unoptimized','Optimized', 'Optimized', 'Optimized', 'Optimized', 'Optimized', 'Optimized')
                )

Here is the code I tried to generate the plots with their labels:

gg1 = df %>% 
  ggplot(aes(x = spend_percentage, y = category, fill = targeting)) + 
  geom_col() + 
  facet_grid(~type) + 
  ggtitle('Budget Percentage by Targetig Type ') + 
  theme(axis.title.y = element_text(colour="gray20", size=12,
                                    angle=90, hjust=.5, vjust=1),
        axis.title.x = element_text(colour="gray20"),
        plot.title = element_text(hjust=-0.5, size = 14),
        axis.text.x = element_text(size=12, angle=0, hjust=.5, vjust=-1.5)) + 
  xlab('Spend Percentage') + 
  geom_text(aes(x = spend_percentage, label = spend_percentage), 
            hjust = -1)

ggplotly(gg1)

enter image description here


Solution

  • Replace hjust = 1 in your geom_text() line with position = position_stack(vjust = 0.5) should do the job.

    gg1 = df %>% 
      ggplot(aes(x = spend_percentage, y = category, fill = targeting)) + 
      geom_col() + 
      facet_grid(~type) + 
      ggtitle('Budget Percentage by Targetig Type ') + 
      theme(axis.title.y = element_text(colour="gray20", size=12,
                                        angle=90, hjust=.5, vjust=1),
            axis.title.x = element_text(colour="gray20"),
            plot.title = element_text(hjust=-0.5, size = 14),
            axis.text.x = element_text(size=12, angle=0, hjust=.5, vjust=-1.5)) + 
      xlab('Spend Percentage') + 
      geom_text(aes(x = spend_percentage, label = spend_percentage), 
                position = position_stack(vjust = 0.5))
    
    ggplotly(gg1)
    

    result