[英]Plotly in R: How to draw stacked bar chart in a time-series data to show percentage composition?
I have a dataframe that looks like this:我有一个看起来像这样的 dataframe:
+------------+------+-------+
| 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.但 x 轴将是日期。
I am drawing this using plotly (not ggplot2, since I would like it to be interactive) using R.我使用 plotly(不是 ggplot2,因为我希望它是交互式的)使用 R 绘制这个。
Thanks very much!非常感谢!
Try with ggplotly
as it can be easier:尝试使用ggplotly
,因为它更容易:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.