【问题标题】:Drawing a multiple line ggplot figure绘制多线 ggplot 图
【发布时间】:2016-09-28 09:38:05
【问题描述】:

我正在研究一个应该在同一个图表上包含 3 条不同线的图形。我正在处理的数据框如下:

我希望能够在 x 轴上使用 ind(我的数据点),然后使用来自 med、b 和 c 列的数据绘制 3 条不同的线。 我只画了一条线。

你能帮帮我吗?我现在使用的代码是

ggplot(data=f, aes(x=ind, y=med, group=1)) + 
  geom_line(aes())+ geom_line(colour = "darkGrey", size = 3) + 
  theme_bw() + 
  theme(plot.background = element_blank(),panel.grid.major = element_blank(),panel.grid.minor = element_blank())   

【问题讨论】:

标签: r dataframe ggplot2 drawing figure


【解决方案1】:

关键是将有问题的列分散到一个新变量中。这发生在下面代码的gather() 步骤中。其余的几乎都是样板 ggplot2。

library(ggplot2)
library(tidyr)

xy <- data.frame(a = rnorm(10), b = rnorm(10), c = rnorm(10),
                 ind = 1:10)

# we "spread" a and b into a a new variable
xy <- gather(xy, key = myvariable, value = myvalue, a, b)

ggplot(xy, aes(x = ind, y = myvalue, color = myvariable)) +
  theme_bw() +
  geom_line()

【讨论】:

    【解决方案2】:

    使用melt和ggplot:

    df$ind <- 1:nrow(df)
    head(df)
               a          b       med         c ind
    1  -87.21893  -84.72439 -75.78069 -70.87261   1
    2 -107.29747  -70.38214 -84.96422 -73.87297   2
    3 -106.13149 -105.12869 -75.09039 -62.61283   3
    4  -93.66255  -97.55444 -85.01982 -56.49110   4
    5  -88.73919  -95.80307 -77.11830 -47.72991   5
    6  -86.27068  -83.24604 -86.86626 -91.32508   6
    
    df <- melt(df, id='ind')
    ggplot(df, aes(ind, value, group=variable, col=variable)) + geom_line(lwd=2)
    

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多