Skip to content
Prev 246467 / 398502 Next

Adding lines in ggplot2

Dear Eduardo,

This a solution that you seem to want

n <- 1:10
x <- sqrt(n)
y <- log(n)
qplot(n, x, geom="line", colour="darkgreen") + geom_line(data =
data.frame(n , x = y), colour="red")

But please compare it with the solution (code + result) below.
Formatting the data.frame might be a bit more work, but formatting your
graph is much easier.

n <- 1:10
dataset <- 
	rbind(
		data.frame(Number = n, Function = "sqrt", Result =
sqrt(n)),
		data.frame(Number = n, Function = "log", Result =
log(n))
)
#Using the default colours
ggplot(dataset, aes(x = Number, y = Result, colour = Function)) +
geom_line()
#Using user-specified colours
ggplot(dataset, aes(x = Number, y = Result, colour = Function)) +
geom_line() + scale_colour_manual(values = c(sqrt = "darkgreen", log =
"red"))

Think about the gain when you want to display much more than 2 lines...

dataset <- expand.grid(Number = n, Power = seq(0, 2, length = 21))
dataset$Result <- dataset$Number ^ dataset$Power
ggplot(dataset, aes(x = Number, y = Result, colour = factor(Power))) +
geom_line()

HTH,

Thierry


------------------------------------------------------------------------
----
ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek
team Biometrie & Kwaliteitszorg
Gaverstraat 4
9500 Geraardsbergen
Belgium

Research Institute for Nature and Forest
team Biometrics & Quality Assurance
Gaverstraat 4
9500 Geraardsbergen
Belgium

tel. + 32 54/436 185
Thierry.Onkelinx at inbo.be
www.inbo.be

To call in the statistician after the experiment is done may be no more
than asking him to perform a post-mortem examination: he may be able to
say what the experiment died of.
~ Sir Ronald Aylmer Fisher

The plural of anecdote is not data.
~ Roger Brinner

The combination of some data and an aching desire for an answer does not
ensure that a reasonable answer can be extracted from a given body of
data.
~ John Tukey