带百分比的R ggplot

时间:2019-10-28 23:19:44

标签: r ggplot2

我正在尝试用百分比而不是计数来绘制条形图,而我已经尝试过了:

ggplot(data = newdf3) + 
  geom_bar(mapping = aes(x = key, y = ..prop..,fill=value,group = 1), stat = "count",position=position_dodge()) + 
  scale_y_continuous(labels = scales::percent_format())

但显然“ group = 1”不起作用,因为它返回的是: graf1

,如果我不使用“ group = 1”,它将返回: graf2

这是我正在使用的数据示例:

key   value

1     Before
1     After
1     During
1     Before
2     Before
2     After
3     During
...


有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

考虑使用geom_col()代替geom_bar()

但是,您应该可以解决stat="identity"的问题。

library(ggplot2)

#sample data.frame
df <- data.frame(
  group = c("A","A","B","B","C","C"),
  value = c(0.1,0.5,0.3,0.1,0.2,0.6)
)
df %>% head

#histogram
df %>% 
  ggplot(aes(x = group)) + 
  geom_bar()

#NOT histogram
df %>% 
  ggplot(aes(x = group, y = value)) + 
  geom_bar(stat = "identity") +
  scale_y_continuous(labels = scales::percent_format())

答案 1 :(得分:0)

一种解决方案是使用您输入的数据计算相对频率,然后使用ggplot中的stat = "identity"参数将结果直接传递到geom_bar(请参阅this post):

library(tidyverse)

df <- tibble::tribble(
  ~key, ~value,
  1, "Before",
  1, "After",
  1, "During",
  1, "Before",
  2, "Before",
  2, "After",
  3, "During"
)

df %>%
  dplyr::count(key, value) %>%
  dplyr::group_by(key) %>%
  dplyr::mutate(p = n / sum(n)) %>%
  ggplot() + 
    geom_bar(
      mapping = aes(x = key, y = p, fill = value),
      stat = "identity",
      position = position_dodge()
    ) + 
    scale_y_continuous(labels = scales::percent_format())

reprex package(v0.3.0)于2019-10-28创建