如何在ggplot中实现绝对百分比刻度?

我正在尝试使用gpplot在堆叠图中绘制正数和负数。根据我在此页面上找到的示例,此方法正常工作。

图形的极限是-1和1,但是我希望比例尺将标签显示为绝对百分比,即从左边的100%超过中心的0%到右边的100%。

下面的最小示例说明我可以获得百分比比例标签(labels = percent)或绝对比例标签(labels = abs),但是我不知道如何将它们组合起来。

谢谢。

library(tidyverse)
library(scales)

x <- tribble(
  ~response,~count,"a",-0.2,"b",-0.1,"c",0.5,"d",0.2
)

p <- ggplot() +
  geom_bar(data = x,aes(x = "",y = count,fill = response),position = "stack",stat = "identity") +
  coord_flip()

# Percent scale
p + scale_y_continuous(labels = percent,limits = c(-1,1),expand = c(0.05,0))

# Absolute scale
p + scale_y_continuous(labels = abs,0))

reprex package(v0.3.0)于2019-11-14创建

d332426126 回答:如何在ggplot中实现绝对百分比刻度?

位置从堆叠更改为躲避。这样就可以在显示不同计数值的同时将变量清零分离。

p <- ggplot() +
  geom_bar(data = x %>% filter(count < 0),aes(x = "",y = count,fill = response),position = "dodge",stat = "identity") +
  geom_bar(data = x %>% filter(count >= 0),stat = "identity") +
  coord_flip()

# Percent scale
p + scale_y_continuous(labels = percent,limits = c(-1,1),expand = c(0.05,0))

# Absolute scale
p + scale_y_continuous(labels = abs,0)) 

输出显示在下面的某个地方。

很好的绘图示例。谢谢,

enter image description here

,

答案在评论中:在 labels = function(x) percent(abs(x)) 中使用 scale_y_continuous()

本文链接:https://www.f2er.com/3105529.html

大家都在问