Ben
Ben

Reputation: 69

100% percentage barplot in R

I have a dataset like so:

enter image description here

I want to create a 100% bar plot from this... such that there is a 100% bar for status, and a 100% bar for Type.... like so: enter image description here

The picture only has 1 bar for status, but I wish for two bars side by side, 1 for status, 1 for type..

Any help would be appreciated, I want to do this in R

Upvotes: 1

Views: 1449

Answers (2)

Edward
Edward

Reputation: 19134

Simple base R solution:

p1 <- as.matrix(prop.table(table(data$status))) * 100
p2 <- as.matrix(prop.table(table(data$Type))) * 100

op <- par(mfrow=c(1,2), las=1, mar=c(3,4,1,0))
barplot(p1, legend=TRUE, names="status", ylab="Percent")
barplot(p2, legend=TRUE, names="Type")
par(op)

enter image description here


data <- data.frame(id=1:10, 
                   status=c("P","F","F","P","F","P","P","F","P","P"),
                   Type=c("full","full","full","part","part","full","full","part","part","full"))

data
   id status Type
1   1      P full
2   2      F full
3   3      F full
4   4      P part
5   5      F part
6   6      P full
7   7      P full
8   8      F part
9   9      P part
10 10      P full

Maybe with ggplot2

data %>%
  pivot_longer(-id) %>%
  group_by(name, value) %>%
  summarise(n=n()) %>%
  ggplot(aes(fill=value, y=n, x=name)) + 
  geom_bar(position="fill", stat="identity") # Needs polishing 

Upvotes: 1

m_ky
m_ky

Reputation: 51

Despite the information provided being a little bit scarce indeed, You seem to look for a stacked barplot with percentages. You might try something like:

# Some sample data:
dta <- tibble(id = 1:10,
              status = rbernoulli(n = 10, p = 0.3),
              type = rbernoulli(n = 10, p = 0.6))

# Transformation and plotting:
dta %>%
  pivot_longer(c(status, type), names_to = "variable") %>%
  group_by(variable, value) %>%
  summarize(percent = n()) %>%
  mutate(percent = percent / sum(percent)) %>%
  ungroup() %>%
  ggplot() +
  aes(x = variable, y = percent, fill = value) +
  geom_bar(stat = "identity") +
  theme_bw()

Resulting in:

Does this help?

Upvotes: 0

Related Questions