我有一个数据框,其中包含两个分类变量,称为验证和过程。
我想制作一个条形图,其中包含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")
答案 0 :(得分:1)
只需将fill = verified
添加到您的初始aes
或geom_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")
g1
和g2
都会产生相同的情节
正如 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")
生产