使用 geom_linerange 对 y 轴条进行排序
Sort the y-axis bars using geom_linerange
我有以下数据。我正在尝试制作赠款表。在这个例子中,我只放了 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。
您可以使用因子反转 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 package (v2.0.1)
于 2022-02-18 创建
我有以下数据。我正在尝试制作赠款表。在这个例子中,我只放了 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。
您可以使用因子反转 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 package (v2.0.1)
于 2022-02-18 创建