Cor*_*rey 2 plot r range bar-chart ggplot2
我想在 R 中创建一个范围条形图。我发现了大约 4 年前发布的类似问题,但答案有点尴尬和麻烦。它完成了工作,但我希望现在可以采用更简洁的方法。使用 ggplot2 是理想的选择。
如果可能的话,我还想包括某种点数据,或其他一些方式来指示汇总统计数据,例如该特定范围的平均值或中位数。
与所附图片相比,项目 ID 将取代沿 y 轴给出的月份,并且“开始”和“结束”值将沿 x 轴水平表示。
尽管数据不必以这种方式构建,但这里有一个示例数据框,可以使事情变得更容易:
structure(list(Item = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20), Start = c(500, 550, 500,
450, 400, 400, 500, 400, 300, 300, 350, 250, 300, 200, 200, 100,
100, 50, 0, 0), End = c(550, 600, 550, 550, 700, 600, 600, 700,
850, 600, 650, 650, 750, 900, 800, 900, 1000, 950, 900, 1000),
Median = c(525, 575, 525, 500, 550, 500, 550, 550, 575, 450,
500, 450, 525, 550, 500, 500, 550, 500, 450, 500)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L), spec = structure(list(
cols = list(Item = structure(list(), class = c("collector_double",
"collector")), Start = structure(list(), class = c("collector_double",
"collector")), End = structure(list(), class = c("collector_double",
"collector")), Median = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))```
Run Code Online (Sandbox Code Playgroud)
geom_segment
根据 RAB 的建议,您可以尝试与您的数据框一起使用df
:
library(ggplot2)
ggplot(data = df)+
geom_segment(aes(x = Item, xend = Item, y = Start, yend = End), size = 5, colour = "red", alpha = 0.6) +
geom_segment(aes(x = Item, xend = Item, y = Median-1, yend = Median+1), size = 5, colour = "black") +
coord_flip() +
scale_x_discrete(limits = as.character(ddf$Item))+
ylab("Value")
Run Code Online (Sandbox Code Playgroud)
或者,您也可以使用geom_crossbar
:
ggplot(data = ddf, aes(x = as.factor(Item), y = Median)) +
geom_crossbar(aes(ymin = Start, ymax = End), width = 0.5, fill = "grey") +
coord_flip() +
xlab("Item") +
ylab("Value")
Run Code Online (Sandbox Code Playgroud)