【问题标题】:Scatter plot time and symbols散点图时间和符号
【发布时间】:2018-07-21 23:19:12
【问题描述】:

我一直在寻找我的问题的答案,但没有成功。 我有一个与此类似的数据集

df <- as.data.frame(cbind(
c("3", "3", "7", "7", "7", "7", "2", "2", "4", "4"),
c("344", "73", "73", "71", "344", "72", "21", "27", "42", "43"),
c(7, 15, 6, 9, 20, 12, 4, 5, 2, 0),
c(2, 2, 5, 5, 3, 6, 3, 3, 3, 3)
))
names(df) <- c("number", "code", "time_1", "time_2")

数据集包含项目(变量“代码”,即具有相同代码编号的所有行都与同一项目有关)和从起点开始的时间(time_1 和 time_2)。变量 time_1 包含不同行的不同时间,但变量 time_2 包含每个项目的相同时间(即具有相同代码的每一行从 time_2 的起点开始具有相同的时间)。

我想在同一行绘制每个项目的时间。我试过下面的代码

library(ggplot2)
ggplot(df, aes(time_1, code)) +
+   geom_point(size=2, col="steelblue") + 
+   theme_bw() +
+   labs(x="Time from start", y="Code")

我的代码有两个问题:

首先 - 我希望能够在 time_1 之后对所有行进行排序,因此 x 轴从 0 到 20。但这似乎不起作用,因为项目 344 的时间 7 出现在情节中的时间 20 之后但不在表格中。

第二 - 我还希望能够在同一个图中为每个项目绘制 time_1 和 time_2,并且变量 time_2 的所有数据在散点图中用另一个符号(例如三角形)表示。

有什么建议对我有帮助吗?

提前谢谢你!

【问题讨论】:

    标签: r plot ggplot2 time scatter-plot


    【解决方案1】:

    这就是你要找的吗?我不得不更改数据类型,因为数据框的设置有点时髦。如果您使用以下数据:

    df <- data.frame(
      number =  c("3", "3", "7", "7", "7", "7", "2", "2", "4", "4"),
      code = c("344", "73", "73", "71", "344", "72", "21", "27", "42", "43"),
      time1 = c(7, 15, 6, 9, 20, 12, 4, 5, 2, 0),
      time2 = c(2, 2, 5, 5, 3, 6, 3, 3, 3, 3)
      )
    

    您不必更改任何数据类型,可以跳到dplyr 链:

    library(tidyr)
    library(ggplot2)
    library(dplyr)
    
    df$code <- as.factor(df$code)
    df$time_1 <- as.integer(df$time_1)
    df$time_2 <- as.integer(df$time_2)
    
    df %>% 
      gather(key, value, -c(code, number)) %>% 
      ggplot(aes(value, code, shape = key)) +
      geom_point(size = 2, col = "steelblue") +
      labs(x = "Time from start", y = "Code") +
      theme_bw()
    

    数据:

    df <- as.data.frame(cbind(
      c("3", "3", "7", "7", "7", "7", "2", "2", "4", "4"),
      c("344", "73", "73", "71", "344", "72", "21", "27", "42", "43"),
      c(7, 15, 6, 9, 20, 12, 4, 5, 2, 0),
      c(2, 2, 5, 5, 3, 6, 3, 3, 3, 3)
    ), stringsAsFactors = FALSE)
    

    【讨论】:

    • 绝对是正确的方向。是否可以将“代码”数字视为标称?因为它们只代表样本的 ID。
    • 太棒了。正是我想要的。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2020-06-20
    • 2021-11-13
    相关资源
    最近更新 更多