3

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?

Quinten
  • 35,235
  • 5
  • 20
  • 53

2 Answers2

2

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

user12728748
  • 8,106
  • 2
  • 9
  • 14
1

Building on user12728748's answer, you can also directly compute the breaks using ggplot's own way with scales::extended_breaks.

NB: for polar coordinates, the limits of the computed breaks seem to be dropped. This seems similar to its behaviour for when the breaks are being used with a guide_legend function on continuous data (see also: How does ggplot calculate its default breaks?). I don't know where exactly this happens - but maybe someone knows an answer to this question.

library(ggplot2)
my_breaks <- scales::extended_breaks()(mtcars$mpg)
my_breaks <- my_breaks[2:(length(my_breaks)-1)] ## in polar coordinates, the limits of the breaks are not used

ggplot(mtcars, aes(x = hp, y = mpg, color = factor(am))) +
  geom_point() +
  coord_polar() +
  labs(color = 'am') +
  annotate('text', x = 0, y = my_breaks, label = my_breaks, size = 9*5/14) +
  theme(axis.text.y = element_blank(), 
        axis.ticks.y = element_blank())

Created on 2023-04-01 with reprex v2.0.2

tjebo
  • 21,977
  • 7
  • 58
  • 94