Reputation: 75
I have a dataframe with data of the daily evolution of the coronavirus with 4 columns: date, active cases, deaths and recoveries. Since the sum of these 3 last values is equal to the total number of cases, I want a bar chart where each day has a corresponding bar divided in 3 parts: active cases, deaths and recoveries. How do I do this with ggplot? Thank you in advance
Upvotes: 0
Views: 266
Reputation: 16178
A possible way is to reshape your dataframe into a longer format using pivot_longer
function for example in order to fit the use with ggplot2
.
As an example with a fake dataset:
library(lubridate)
df <- data.frame(date = seq(ymd("2020-01-01"),ymd("2020-01-10"),by = "day"),
active = sample(10:100,10),
death = sample(10:100,10),
recov = sample(10:100,10))
library(dplyr)
library(tidyr)
library(ggplot2)
df %>% pivot_longer(-date, names_to = "case", values_to = "val") %>%
mutate(case = factor(case, levels = c("active","recov","death"))) %>%
ggplot(aes(x = date, y = val, fill = case))+
geom_col(position = position_stack(reverse = TRUE))
Does it answer your question ?
If not, please provide a reproducible example of your dataset by following this guide: How to make a great R reproducible example and the code you have try so far.
Upvotes: 1