ggplot2()条形图填充参数

时间:2017-11-19 23:30:55

标签: r ggplot2

我有一个数据框,其中包含两个分类变量,称为验证和过程。

我想制作一个条形图,其中包含x轴上的程序,以及相应的百分比,而不是y轴上的计数。此外,我想验证是酒吧的填充。

问题在于,当我尝试使用fill参数时,它没有用。我当前的代码为我提供了全黑的条形图(尽管没有填充参数,黑线似乎表示已验证的水平???)。相反,我希望水平有不同的颜色。

谢谢!

起点(df):

df <- data.frame(verified=c("small","large","small","small","large","small","small","large","small"),procedure=c(1,2,1,2,1,2,2,2,2)) 

当前代码:

library(dplyr)
library(gglot2)
df  %>%
  count(procedure,verified) %>%
  mutate(prop = round((n / sum(n))*100),2)  %>%
  group_by(procedure)  %>% 
    ggplot(aes(x = procedure, y = prop)) +
    geom_bar(stat = "identity",colour="black") 

1 个答案:

答案 0 :(得分:1)

只需将fill = verified添加到您的初始aesgeom_bar

# common elements
g_df <- df %>%
  count(procedure, verified) %>%
  mutate(prop = round((n / sum(n)) * 100), 2) %>%
  group_by(procedure)

# fill added to initial aes
g1 <- ggplot(g_df, aes(x = procedure, y = prop, fill = verified)) +
  geom_bar(stat = "identity", colour = "black")

# fill added to geom_bar
g2 <- ggplot(aes(x = procedure, y = prop)) +
  geom_bar(aes(fill = verified), stat = "identity", colour = "black")

g1g2都会产生相同的情节

enter image description here

正如 eipi10 在我的回答评论中所建议的那样,您可以通过将xaxis作为factor进行清理,修改下面的代码。

df %>%
  count(procedure, verified) %>%
  mutate(prop = n / sum(n)) %>%
  ggplot(aes(x = factor(procedure), y = prop, fill = verified)) +
  geom_bar(stat = "identity", colour = "black") +
  labs(x = "procedure", y = "percent")

生产

enter image description here