ggplot2()条形图填充参数 [英] ggplot2() bar chart fill argument

查看:183
本文介绍了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")

g1g2都在下面产生相同的图

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")

生产

这篇关于ggplot2()条形图填充参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆