LLL
LLL

Reputation: 743

ggplot2() bar chart fill argument

I've got a data frame with two categorical variables called verified and procedure.

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.

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.

Thanks!

starting point (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)) 

current code:

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

Upvotes: 0

Views: 1860

Answers (1)

Kevin Arseneau
Kevin Arseneau

Reputation: 6264

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

Both g1 and g2 produce the same plot below

enter image description here

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

to produce

enter image description here

Upvotes: 1

Related Questions