如何在 ggplot 的 coord_polar 图表内添加纵轴标签?

3

我想在使用coord_polargeom_point绘制的图中自动添加y轴标签。以下是一个可重现的示例:

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

使用 reprex v2.0.2 创建于2022-10-31

在这里,你可以看到 y 轴的标签位于极坐标图的外部,但我希望它们能够在内部。我知道你可以像这样使用 annotate

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')) 

使用reprex v2.0.2于2022-10-31创建

但这并不是很自动化。所以我想知道是否有一种自动添加y轴标签到像上面那样的coord_polar图表的方法?


也许可以通过创建一个自定义的注释函数来实现这个目的? - Maël
2个回答

2
让您开始:您可以提取休息时间并应用它们,以使其至少“半自动化”:
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))

创建于2022年10月31日,使用reprex v2.0.2

1

在user12728748的答案基础上,您还可以直接使用ggplot自己的方法计算断点,方法是使用scales::extended_breaks

注意:对于极坐标,计算出的断点限制似乎被删除了。这类似于在连续数据上使用guide_legend函数时断点的行为(也请参见:ggplot如何计算其默认断点?)。我不知道这发生在哪里 - 但也许有人知道这个问题的答案

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())

使用reprex v2.0.2于2023年4月1日创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接