【问题标题】:Create a Range Bar Chart in R在 R 中创建范围条形图
【发布时间】:2019-12-04 04:05:44
【问题描述】:

我想在 R 中创建一个范围条形图。 我发现了一个大约 4 年前发布的类似问题,但答案有点尴尬和麻烦。它完成了这项工作,但我希望现在可能有一种更清洁的方法。使用 ggplot2 将是理想的选择。

Floating bar chart with dates as the plotted values in r

如果可能的话,我还想包含某种点数据,或某种其他方式来表示汇总统计数据,例如该特定范围的平均值或中位数。

与所附图片相比,项目 ID 将取代沿 y 轴给出的月份,而 Start 和 End 值将沿 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"))```

示例图片取自“AnyChart”网站上的范围条形图条目。

【问题讨论】:

  • 你可以使用geom_segment来获得这样的酒吧

标签: r ggplot2 plot range bar-chart


【解决方案1】:

根据 RAB 的建议,您可以尝试将 geom_segment 与您的数据框 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")

或者,您也可以使用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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多