My data is:
positive <- c("21", "22", "33", "21", "27") ##Percentage
negative<- c("71", "77", "67", "79", "73") ##Precentage
sample <- c("Hr", "Fi", "We", "Pa", "Ki")
mydata <- data.frame(positive , negative, sample)
I want to create a stacked bar graph that shows positive and negative percentages for each category in the sample variable. I tried this:
ggplot(mydata)
geom_bar(aes(x = sample, fill = positive))
but did not wrok. Sorry if the question looks basic. I started R a few weeks ago.
CodePudding user response:
This probably serves your purpose:
library(tidyverse)
mydata %>% pivot_longer(cols = !sample, names_to = "status", values_to = "percentage") %>%
ggplot(aes(fill = status, x = sample, y = percentage))
geom_bar(position = "stack", stat = "identity")
CodePudding user response:
You need to pivot your data to long format first (tidy format). Then, we can specify the x (sample
), y (value
), and fill (name
) conditions.
library(tidyverse)
mydata %>%
pivot_longer(-sample) %>%
ggplot(aes(fill = name, y = value, x = sample))
geom_bar(position = "stack", stat = "identity")
Output
CodePudding user response:
Here is an alternative approach using values_transform
to get numeric type and then using geom_col
with position_fill
and percentage features:
library(dplyr)
library(tidyr)
library(ggplot)
library(scales)
mydata %>%
pivot_longer(
cols = -sample,
names_to = "status",
values_to = "percentage",
values_transform = list(percentage = as.integer)
) %>%
ggplot(aes(x = sample, y=percentage, fill=status))
geom_col(position = position_fill())
scale_y_continuous(labels = scales::percent)
geom_text(aes(label = percentage),
position = position_fill(vjust = .5))