R语言 如何动态更改ggplot标签的符号,而不更改底层数据?

hwamh0ep  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(60)

我在ggplot中创建了一个人口金字塔,为了让条形图正确显示,我将一个类别的符号乘以-1改为负数。
现在的问题是,我有酒吧看起来正确,但轴标签显示负数。我想知道我如何动态地改变符号(即)。我不能手动指定特定的标签,因为图表是在循环中创建的,有些图表会有不同的范围)。下面是绘图和图像的代码。
谢谢你

PyramidPlot <- ggplot() +
  geom_bar(data = PopEDMalesFullLessT, aes(x = Age, y = Percentage, fill = "red"), width= 0.4, 
           position = position_nudge(0.22), stat = "identity") +
  geom_bar(data = PopEDFemalesFullLessT, aes(x =  Age, y = Percentage, fill = "blue"), width= 0.4,
           position = position_nudge(0.22), stat = "identity") +
  scale_x_discrete(name = "Age Group")+
  labs(fill = "Legend") +
  theme_classic()+
  theme(axis.text.x = element_text(margin = margin(t = 0.25, unit = "in")),
        axis.title.x = element_text(margin = margin(0.1, 0, 0.1, 0)),
        legend.position = c(0.9, 0.9)
  )+
  coord_flip()+
  scale_fill_discrete(labels=c('Males', 'Females'))

6kkfgxo0

6kkfgxo01#

您可以给予ggplot scale的labels参数函数,在这种情况下,该函数将应用于默认标签。在这种情况下,绝对值函数abs将起作用。有关详细信息和其他选项,请参阅?continuous_scale

data.frame(x = 1:3, y = (-1):1) |> 
  ggplot(aes(x, y)) + geom_point() + 
  scale_y_continuous(labels = abs)

相关问题