当前位置: 动力学知识库 > 问答 > 编程问答 >

r - connect points in ggplot based on specific column values

问题描述:

I have the following data set called t:

n <- 12

t <- data.frame(

V1 = runif(n, 0.12, 0.35),

V2 = runif(n, 0.25, 0.39),

group = gl(3, 4, labels = c("a1", "a2", "a3")),

x = seq_len(n),

color = rep(rep.int(c("R", "G"), 2), c(3, 4, 3, 2))

)

I created the following plot from this data.

p <- ggplot(t, aes(x, colour = color)) +

geom_point(aes(y = V1, size = 10)) +

geom_point(aes(y = V2, size = 10))

What I want to do now is to connect the points depending on the group column (e.g, points of group a1 will be connected with a blue line, points of group a2 will be connected in a yellow line, ...) and i want the line to be different depending on V1 and V2 (dashed line for V1 and normal line for V2).

How this can be done?

网友答案:

First of all: naming a dataset "t" is not a good idea because it is confusing since there is a function t() as well.

The easiest way is to melt() your dataset first

Molten <- melt(t, id.vars = c("group", "x", "color"))
ggplot(Molten, aes(x = x, y = value, colour = group, linetype = variable)) + geom_line()

Have a look at the ggplot2 website on how to customise the colours.

网友答案:

If you want to plot your graph without using melt():

p <-ggplot(t) + geom_line(aes(x,V2,color=group)) + geom_line(aes(x,V1,color=group), linetype = "dashed")
分享给朋友:
您可能感兴趣的文章:
随机阅读: