【问题标题】:Make plot defining X values based on column numbers/names in R根据 R 中的列号/名称绘制定义 X 值的图
【发布时间】:2017-11-18 20:45:05
【问题描述】:

我正在尝试在 R 中绘制一个图,其中 X 轴值对应于特定列,其中水平线逐行连接 y 轴(如使用 matplot 函数)。例如:

set.seed(23); dt <- matrix(runif(18, 0, 1), nrow = 3, ncol=6)

> dt
          [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
[1,] 0.5766037 0.7107246 0.9635445 0.9966112 0.3904731 0.1392785
[2,] 0.2230729 0.8194490 0.9781304 0.8659590 0.3147697 0.5181206
[3,] 0.3318966 0.4237206 0.8405219 0.7014217 0.8459473 0.5935508

我想绘制 x-2=col 1、x-1= col 2、x0=col 3、x1=col 4、x2=col 5、x3=col 6 等,并用一条线连接每行的 y 值。

您知道如何以简单的方式完成此操作吗?谢谢!

【问题讨论】:

    标签: r plot axis


    【解决方案1】:
    set.seed(23)
    dt <- matrix(runif(18, 0, 1), nrow = 3, ncol=6)
    
    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    data.frame(dt) %>%                              # save it as dataframe
      mutate(id = factor(row_number())) %>%         # add row number as a variable
      gather(key,value,-id) %>%                     # reshape dataset
      ggplot(aes(key, value, group=id, col=id)) +   # plot data by grouping on id
      geom_point() +                                # add points
      geom_line()                                   # add lines
    

    颜色 (id) 代表初始表中的行。 X 轴代表初始表中的列。

    【讨论】:

    • 感谢您的解决方案。但是不使用 ggplot2 包还有其他方法吗?我认为使用 ggplot2 包语法对图表进行更改非常困难
    • 我是 ggplot 用户,但您可以在 ggplot 命令之前运行该过程并将其保存为新数据集。然后,您可以使用它使用基本 R 命令创建绘图。
    • 好的,谢谢。我刚刚发现matplot函数也可以是一个简单的解决方案:matplot(t(dt), type="l")
    猜你喜欢
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    相关资源
    最近更新 更多