【问题标题】:Simple Gantt chart with R (plotting multiple lines)带有 R 的简单甘特图(绘制多条线)
【发布时间】:2019-08-12 13:07:37
【问题描述】:

我想用 RShiny 和 ggplot2 创建一个非常简单的甘特图。我不想使用包或预定义的甘特图like here。我宁愿通过将多条线绘制在另一条之上并且全部平行来创建图表。应该不是很难,但是图表后面的数据框有问题。

我有一个非常简单的数据框,例如:

test_df_1 <- data.frame("x_1" = c(1,2,3),
                        "x_2" = c(2,4,5),
                         "y" = c(1,2,3),
                         "group" = c("A","B","C"))

对于 y = 1,行应该是从 1 到 2,对于 y = 2,行应该是从 2 到 4,等等。使用这些代码行,我得到一个空图(但没有错误消息):

  output$test <- renderPlot({
       df_test <- data.frame(x_1=unlist(test_df_1$x_1), x_2=unlist(test_df_1$x_2), 
                             y=unlist(test_df_1$y), group=unlist(test_df_1$group))

       ggplot(data=df_test, aes(x=x_1, y=y, group=y)) +
          geom_line() +
          theme_bw()
       })

我确定我没有将 x_2 “导入”到 ggplot 中。但我不知道该怎么做。

当我以稍微不同的顺序尝试数据框时(我实际上不想要):

test_df_2 <- data.frame("x_1" = c(1,2,2,4,3,5),
                        "y" = c(1,1,2,2,3,3),
                         "group" = c("A","","B","","C",""))

并绘制它:

  output$test <- renderPlot({
       df_test <- data.frame(x_1=unlist(test_df_2$x_1), 
                             y=unlist(test_df_2$y), group=unlist(test_df_2$group))

       ggplot(data=df_test, aes(x=x_1, y=y, group=y)) +
          geom_line() +
          theme_bw()
       })

我得到了预期的result。

如何使用第一个数据框 (test_df_1) 的结构获得所需的多线图?

【问题讨论】:

  • 来自R for Data Science dplyr、ggplot2 以及 tidyverse 中的所有其他包都是为了处理 tidyverse 数据而设计的......,所以你需要转移test_df_1类似于test_df_2

标签: r ggplot2 shiny gantt-chart line-plot


【解决方案1】:
ggplot(data=df_test) +
  geom_linerange(aes(x = y, ymin = x_1, ymax = x_2)) +
  coord_flip()+
  theme_bw()

或不翻转:

ggplot(df_test, aes(x = x_1, y = y, group = group)) + 
  geom_segment(aes(xend = x_2, yend = y))

【讨论】:

  • 太棒了!第一个工作完美。但在“不翻转”时,线条是垂直排列的。
  • 这很奇怪,因为每个版本的情节都一样
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多