【问题标题】:How to plot multiple lines quickly in R using plot or ggplot2如何使用 plot 或 ggplot2 在 R 中快速绘制多条线
【发布时间】:2016-09-14 20:10:58
【问题描述】:

我有一个数据框(见下文),它比显示的多行,通过 Fly 列标记(每行都是唯一的),并且每行接收到的条件都通过条件列标记。每条线都有在不同时间进行的四个与之相关的测量值。我想将 X 上的音量绘制为音量,将 Y 绘制为时间。和颜色代码由 Fly 下的唯一行显示。有没有一种快速简便的方法来做到这一点?不确定如何让它工作或从 ggplot2() 甚至 plot() 开始。一些帮助和指导将不胜感激。

     Fly condition_1 volume_1 volume_2 volume_3 volume_4
1     1    postcont      1.6     18.0      8.1     13.5
2     2    postcont      0.0     12.0     10.1      8.5
3     3    postcont      2.6      3.0     10.1      1.5
4     4    postcont     13.6     13.0     10.1     15.5

这是绘制的代码

data1<-read.table(file=file.choose(),header=T)
head(data1)
postcontexp<-subset(data1, condition_1 == "postcont")
postcontexpVOL<- subset(# to remove unwanted columns)
postcontexpVOL<- na.omit(postcontexpVOL)

【问题讨论】:

  • 抱歉,这里不是要求提供有关绘图基础知识的自定义教程的好地方。如果你look at the R tag wiki,有很多免费的 R 入门资源。你也可以在 Stack Overflow 上搜索其他问题。如R plot multiple lines on one graph
  • 您的数据不整齐,这使得绘图变得困难,因为如果您没有时间变量,则很难绘制时间,因为该信息被困在您的列名中。首先重塑,例如library(tidyverse) ; df %&gt;% gather(time, volume, starts_with('volume')) %&gt;% mutate(time = parse_number(time))
  • @Gregor,我了解绘图的一些基础知识。我只是不想多次使用 abline()。

标签: r plot ggplot2


【解决方案1】:

这是使用reshape2dplyr 中的melt 来调整数据的版本:

n <- 4
df <-
  data.frame(
    Ind = 1:n
    , vol_1 = rnorm(n)
    , vol_2 = rnorm(n)
    , vol_3 = rnorm(n)
    , vol_4 = rnorm(n)
  )


melted <-
  melt(df, id.vars = "Ind") %>%
  mutate(Time = as.numeric(gsub("vol_","",variable)))

ggplot(melted
       , aes(x = Time
             , y = value
             , col = as.factor(Ind))) +
  geom_line()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    相关资源
    最近更新 更多