I have a dataframe that looks like this:
+------------+------+-------+
| Date | Boys | Girls |
+------------+------+-------+
| 2020-01-01 | 53 | 78 |
+------------+------+-------+
| 2020-01-02 | 23 | 30 |
+------------+------+-------+
| 2020-01-03 | 45 | 20 |
+------------+------+-------+
| 2020-01-04 | 120 | 178 |
+------------+------+-------+
| 2020-01-05 | 57 | 58 |
+------------+------+-------+
| ... | ... | ... |
+------------+------+-------+
I would like to draw a stacked bar chart across time, to show what percentage of the total is boys vs. what percentage of the total is girls.
It would looks something like this chart:
But the x axis would be dates.
I am drawing this using plotly (not ggplot2, since I would like it to be interactive) using R.
Thanks very much!
Try with ggplotly
as it can be easier:
library(plotly)
library(ggplot2)
library(dplyr)
library(tidyr)
#Code 1
ggplotly(df %>% pivot_longer(-Date) %>%
mutate(Date=as.Date(Date)) %>%
ggplot(aes(x=Date,y=value,fill=name))+
geom_bar(stat = 'identity')+
labs(fill='Var'))
#Code 2
ggplotly(df %>% pivot_longer(-Date) %>%
mutate(Date=as.Date(Date)) %>%
ggplot(aes(x=Date,y=value,fill=name))+
geom_bar(stat = 'identity',position = 'fill')+
labs(fill='Var')+
scale_y_continuous(labels = scales::percent))
Outputs:
Some data used:
#Data
df <- structure(list(Date = c("2020-01-01", "2020-01-02", "2020-01-03",
"2020-01-04", "2020-01-05"), Boys = c(53L, 23L, 45L, 120L, 57L
), Girls = c(78L, 30L, 20L, 178L, 58L)), row.names = c(NA, -5L
), class = "data.frame")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.