我有以下資料。我正在嘗試制作贈款圖表。在示例中,我只放了 4 個 id,但在原始版本中,我有大約 30 個唯一 id。
structure(list(start_date = structure(c(14365, 14914, 14214,
15400, 10957, 10957, 10957, 10957), class = "Date"), treated = c(1,
1, 1, 1, 0, 0, 0, 0), end_date = structure(c(17896, 17896, 17896,
17896, 14364, 14913, 14213, 15399), class = "Date"), id = c("A",
"B", "D", "G", "A", "B", "D", "G")), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -8L))
我正在使用以下代碼來繪制它。
ggplot(df_input)
geom_linerange(aes(y = id,
xmin = start_date,
xmax = end_date,
colour = as.factor(treated)),
size = I(5))
我無法按字母順序對 y 條進行排序,我嘗試在繪圖之前對其進行排序但沒有成功。從上到下我想要A,然后是B,依此類推。另外,如何將條形開始的位置(2000)與 y 標簽 A、B、D 和 G 之間的差距減小到 0。
uj5u.com熱心網友回復:
您可以通過使用因子來反轉 y 值的順序 - 我在呼叫 ggplot 時完成了此操作,但它可以在資料框中完成。
expand使用軸比例的引數管理資料周圍的填充。
library(ggplot2)
library(forcats)
df_input <- structure(list(start_date = structure(c(14365, 14914, 14214,
15400, 10957, 10957, 10957, 10957), class = "Date"), treated = c(1,
1, 1, 1, 0, 0, 0, 0), end_date = structure(c(17896, 17896, 17896,
17896, 14364, 14913, 14213, 15399), class = "Date"), id = c("A",
"B", "D", "G", "A", "B", "D", "G")), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -8L))
ggplot(df_input)
geom_linerange(aes(y = fct_rev(id),
xmin = start_date,
xmax = end_date,
colour = as.factor(treated)),
size = I(5))
scale_x_date(expand = expansion(mult = c(0, 0.05)))

由reprex 包于 2022-02-18 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427625.html
