使用 ggplot 绘制多列的值

Plotting values from multiple columns using ggplot

我有data.frame如下

test=data.frame(start=rep("0",10),end=rep("100",10),Typ1=c("530","630","500","400","350","600","1032","378","430","567"),Type2=c("100","70","50","120","130","50","75","86","90","95"),Type3=c("10","50","40","22","13","45","15","36","19","20"))
>test
start end Type1 Type2 Type3
0     100  530   100    10
0     100  630    70    50
0     100  500    50    40
0     100  400   120    22
0     100  350   130    13
0     100  600    50    45
0     100 1032    75    15
0     100  378    86    36
0     100  430    90    19
0     100  567    95    20

我只想绘制上面的数据框,其中 x 轴表示开始和结束,Y 轴表示 Type1、Type2 和 Type3。 我尝试了以下代码,但它抛出了错误

ggplot(test,aes(x=c(start,end)),y=c(Type1,Type2,Type3)) +geom_density()

请指导我。提前致谢。

我不确定我是否正确理解了您的问题,但我假设您想要三个变量 Type1、Type2、Type3 的密度图,并且值表示线的高度。然后你可以这样做:

test = data.frame(x = seq(0, 100, length.out = 10),
                  Type1 = c(530, 630, 500, 400, 350, 600, 1032, 378, 430, 567),
                  Type2 = c(100, 70, 50, 120, 130, 50, 75, 86, 90, 95),
                  Type3 = c(10, 50, 40, 22, 13, 45, 15, 36, 19, 20))

ggplot(test, aes(x = x)) +
   geom_line(aes(y = Type1, color = "Type 1")) +
   geom_line(aes(y = Type2, color = "Type 2")) +
   geom_line(aes(y = Type3, color = "Type 3"))

您需要做的是为 data.frame 的每一列使用自己的图层。

你的数据框已经安排好了,你不需要在数据框中指定开始和结束。

ggplot 期望 df 中的每一行都是一个观察值,每一列都是一个变量。这意味着我们需要重塑数据

library(tidyverse)
test <- data.frame(start=rep("0",10), end=rep("100",10), 
               Type1=c("530","630","500","400","350","600","1032","378","430","567"),
               Type2=c("100","70","50","120","130","50","75","86","90","95"),
               Type3=c("10","50","40","22","13","45","15","36","19","20"))

注意我修正了一个错字。我们现在可以改造它。您可以在此处阅读更多相关信息 (tidy)。

df <- gather(test, key = 'Type', value = 'Value', contains('type'))

contains 指示使用哪些变量来填充值列。 key 和 value 只是指示给列赋予哪些名称。

> head(df)
  start end  Type Value
1     0 100 Type1   530
2     0 100 Type1   630
3     0 100 Type1   500
4     0 100 Type1   400
5     0 100 Type1   350
6     0 100 Type1   600

我们现在可以使用 ggplot 轻松绘制它。

ggplot(df, aes(x = Value, group = Type, fill = Type, color = Type)) + 
  geom_density(alpha = 0.3)

首先,将数据转换为长格式(对 ggplot 效果更好), 然后绘制

我还创建了一些 x 值...

library(data.table)
library(ggplot2)
plotdata <- setDT(test)[, x := seq(0,100,length.out = 10)]
plotdata <- melt( setDT(test), id.vars = c("x"), measure.vars = patterns("^Typ"), value.factor = FALSE )

ggplot( data = plotdata, 
    aes( x = value, 
         color = variable,
         fill = variable)
    ) + 
  geom_density()