ggplot2()条形图填充参数
我有一个数据帧,其中包含两个类别变量,分别称为verified和procedure.
I've got a data frame with two categorical variables called verified and procedure.
我想制作一个条形图,在x轴上带有过程,并在y轴上带有相应的百分比而不是计数.此外,我想验证一下这些条形图.
I'd like to make a bar chart with procedure on the x-axis, and the corresponding percentages rather than counts on the y-axis. Furthermore, I'd like for verified to be the fill of the bars.
问题在于,当我尝试使用fill参数时,它不起作用.我当前的代码使我的条形全为灰色,并带有黑线(尽管没有填充参数,黑线似乎表明已验证的水平?).相反,我希望级别使用不同的颜色.
The problem's that when I've tried using the fill argument it hasn't worked. My current code gets me bars that are all grey with a black line (despite the absence of a fill argument the black line seems to indicate the levels of verified???). Instead I'd like the levels to be in different colours.
谢谢!
起点(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")
只需将fill = verified
添加到您的初始aes
中或您的geom_bar
just add fill = verified
to your initial aes
or within your 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
都在下面产生相同的图
Both g1
and g2
produce the same plot below
正如 eipi10 在对我的答案的评论中所建议的那样,您可以通过将xaxis
设置为factor
(以下代码的修改)来清理xaxis
.
As suggested by eipi10 in the comments to my answer, you could clean up the xaxis
by making it a factor
, a modification of their code below.
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")
生产