【问题标题】:R multiple line plot using a dataframe [duplicate]使用数据框的R多线图[重复]
【发布时间】:2017-04-09 08:58:42
【问题描述】:

我似乎不知道如何为多条线图创建图形。

这是我的数据框:

   topics before_event after_event current
1       1        0.057       0.044   0.064
2       2        0.059       0.055   0.052
3       3        0.058       0.037   0.044
4       4        0.036       0.055   0.044
5       5        0.075       0.064   0.066
6       6        0.047       0.045   0.045
7       7        0.043       0.043   0.041
8       8        0.042       0.041   0.046
9       9        0.049       0.046   0.039
10     10        0.043       0.060   0.045
11     11        0.054       0.054   0.062
12     12        0.065       0.056   0.068
13     13        0.042       0.045   0.048
14     14        0.067       0.054   0.055
15     15        0.049       0.052   0.053

dataframe中的变量都是数值向量,例如:

主题

我知道我应该使用“ggplot2”和“reshape”,但我似乎无法计算出正确的代码来表示 x 轴上的 主题,比例为 0-1 y 轴,每个 var (before_event, after_event, current) 作为三个单独的行。

任何帮助将不胜感激!

【问题讨论】:

  • 学习搜索。使用[r] multiple line plot 并按投票排序。副本是最佳答案。

标签: r plot ggplot2 linechart reshape2


【解决方案1】:

我们可以从base R使用matplot

matplot(df1[,1], df1[-1], type = 'l', xlab = "topics", ylab = "event", col = 2:4, pch = 1)
legend("topright", legend = names(df1)[-1], pch = 1, col=2:4)

【讨论】:

    【解决方案2】:

    我们可以使用 ggplot 和 geom_line

    library(ggplot2)
    
    topics <- seq(1,15,1)
    before_event <- runif(15, min=0.042, max=0.070)
    after_event <- runif(15, min=0.040, max=0.065)
    current <- runif(15, min=0.041, max=0.066)
    
    df <- data.frame(topics,before_event,after_event,current) #create data frame from the above vectors
    
    df.m <- melt(df, id.vars="topics") # melt the dataframe using topics as id
    
    # plot the lines using ggplot and geom_line
    ggplot(data = df.m,
           aes(x = topics, y = value, group = variable, color = variable)) +
    geom_line(size = 2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2021-12-17
      • 2016-02-05
      • 2022-06-11
      • 2018-04-13
      • 2014-11-09
      • 2021-11-15
      相关资源
      最近更新 更多