[英]Stacked geom_bar plot with dates
我正在嘗試按日期(每月),按組創建堆積的geom_bar圖表,該圖表按日期(每月)顯示會話的累計數量。 由於某些原因,即使我的x變量日期都從2016-11-01開始並在2019-02-01結束,兩組的繪圖都從2015-12-01(Dec-2015)開始,並且所有值都聚集在1月16日,1月17日...等等
當我的日期是字符時,它可以工作,但是后來我無法重新排序。 因此,我將它們更改為日期,但現在遇到了上述問題。
recruitment_tally<-structure(list(dates = structure(c(16811, 16812, 17167, 17168,
17169, 17170, 17171, 17172, 17173, 17174, 17175, 17176, 17177,
17178, 17532, 17533, 17534, 17535, 17536, 17537, 17538, 17539,
17540, 17541, 17542, 17543, 17897, 17898, 17899, 16811, 16812,
17167, 17168, 17169, 17170, 17171, 17172, 17173, 17174, 17175,
17176, 17177, 17178, 17532, 17533, 17534, 17535, 17536, 17537,
17538, 17539, 17540, 17541, 17542, 17543, 17897, 17898, 17899
), class = "Date"), group = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L), .Label = c("control", "mtbi"), class = "factor"),
total_sessions = c(4, 8, 11, 15, 19, 21, 27, 33, 35, 38,
41, 44, 47, 48, 51, 53, 56, 58, 59, 62, 63, 63, 66, 67, 69,
70, 71, 72, 73, 0, 0, 0, 2, 3, 5, 8, 10, 15, 18, 20, 27,
28, 28, 32, 34, 36, 36, 39, 41, 41, 43, 49, 50, 53, 57, 58,
60, 63)), row.names = c(NA, -58L), spec = structure(list(
cols = list(date = structure(list(), class = c("collector_character",
"collector")), group = structure(list(), class = c("collector_character",
"collector")), culm_total = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector"))), class = "col_spec"), class = c("tbl_df",
"tbl", "data.frame"))
library(ggplot2)
base<- recruitment_tally %>%
ggplot()+
geom_bar(aes(y = total_sessions, x= dates, fill = group),
stat="identity",position="dodge") +
coord_flip()
base + scale_x_date(date_breaks = "month", date_labels = "%b%y")
我認為這里發生的是CSV導入后的日期與預期的不一樣。
示例數據中的日期似乎是每個月的前12天。 我假設您想要的是一年中12個月中的每一天的第一天。 我懷疑在此過程中的某處,以年-日-月-月格式表示的日期變成了年-月-日。
您可以使用以下數據來解決此問題:
recruitment_tally %>%
mutate(dates = as.Date(as.character(dates), "%Y-%d-%m")) %>%
ggplot(aes(dates, total_sessions)) +
geom_col(aes(fill = group)) +
coord_flip() +
scale_x_date(date_labels = "%b %Y")
但是更好的解決方法是在導入數據時使日期格式正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.