ceth
ceth

Reputation: 45325

Two lines on one graph

How can I draw two lines on one graph. Here is my code:

data <- read.csv(file='best_duty_distribution.csv', header = TRUE, sep = " ")

ggplot() +
  geom_line(data, aes(x=p1_b, y=b1, color = "red")) +
  geom_line(data, aes(x=p1_b, y=f1, color = "blue")) 

But I get the error:

Ошибка: ggplot2 doesn't know how to deal with data of class uneval

This code works fine, but draw only one line:

ggplot(data, aes(x=p1_b, y=b1)) + geom_line() + geom_point()

Update:

Example of data:

> head(data, 4)
  p1_b p2_b p3_b b1 f1 b2 f2 b3  f3  X
1    0    0    0  0 40  0 20  0 160 NA
2    0    0    1  0 40  0 20  4 152 NA
3    0    0    2  0 40  0 20  8 144 NA
4    0    0    3  0 40  0 20 12 136 NA

Upvotes: 0

Views: 130

Answers (3)

James
James

Reputation: 66844

geoms expect the first unnamed argument to be the mapping and the second the data. Either name your arguments or reverse them:

ggplot() +
  geom_line(data=data, aes(x=p1_b, y=b1, color = "red")) +
  geom_line(data=data, aes(x=p1_b, y=f1, color = "blue"))

or,

ggplot() +
  geom_line(aes(x=p1_b, y=b1, color = "red"), data) +
  geom_line(aes(x=p1_b, y=f1, color = "blue"), data)

Upvotes: 1

Harpal
Harpal

Reputation: 12587

Try this for small plots, you can build the plot yourself:

> df <- data.frame(x=1:6,y1=1:6,y2=2:7)
> ggplot(df, aes(x)) + geom_line(aes(y=y1,colour="blue")) + geom_line(aes(y=y2,colour="red"))

This makes:

enter image description here

You can also melt the data:

> library(reshape)
> df2 <- melt(df,id="x")
> ggplot(df2, aes(x=x,y=value,colour=variable)) + geom_line()

Upvotes: 1

Victorp
Victorp

Reputation: 13856

I don't know what your data looks like, but this draw two lines :

df <- data.frame(a=1:15, x=rnorm(15), y=rnorm(15))
library(ggplot2)
p <- ggplot(df, aes_string(x="a", y="x")) + geom_line(colour="red")
p <- p + geom_line(data=df, aes_string(x="a", y="y"), colour="blue")
p

Upvotes: 1

Related Questions