Home > OS >  How to add y-axis labels inside coord_polar graph ggplot?
How to add y-axis labels inside coord_polar graph ggplot?

Time:11-01

I would like to add the y-axis labels automatically inside a coord_polar plot with geom_point. Here is a reproducible example:

library(ggplot2)
ggplot(mtcars, aes(x = hp, y = mpg, color = factor(am)))  
  geom_point()  
  coord_polar()  
  labs(color = 'am')

Created on 2022-10-31 with reprex v2.0.2

Here you can see the y-axis labels are on the side, but I want them to be inside the polar graph. I know you could use annotate like this:

library(ggplot2)
ggplot(mtcars, aes(x = hp, y = mpg, color = factor(am)))  
  geom_point()  
  coord_polar()  
  labs(color = 'am')  
  annotate('text', x = 0, y = c(15, 20, 25, 30), label = c('15', '20', '25', '30')) 

Created on 2022-10-31 with reprex v2.0.2

But this isn't very automatic. So I was wondering if there is an automatic way of adding y-axis labels inside a coord_polar graph like the above?

CodePudding user response:

To get you started: You could extract the breaks and apply those to make it at least "semi-automatic":

library(ggplot2)
p1 <- ggplot(mtcars, aes(x = hp, y = mpg, color = factor(am))) 
brk <- ggplot_build(p1)$layout$panel_params[[1]]$y$breaks
brk <- brk[-c(1, length(brk))]

ggplot(mtcars, aes(x = hp, y = mpg, color = factor(am)))  
  geom_point()  
  coord_polar()  
  labs(color = 'am')  
  theme(axis.ticks.y=element_blank(),
      axis.text.y=element_blank()) 
  annotate('text', x = 0, y = brk, label = as.character(brk))

Created on 2022-10-31 with reprex v2.0.2

  • Related