Home > other >  ggplot - is it at all possible to draw multiple lines without grouping data
ggplot - is it at all possible to draw multiple lines without grouping data

Time:05-09

I am currently writing a theoretical article where no data is used and unfortunately I must say that I find ggplot hard to use in such applications for showing theoretical examples. I've been using ggplot for years on real, empirical data and there I liked ggplot very much. However, consider my current case. I am trying to plot two exponential functions together on a graph. One function is 0.5^x and the other one is 0.8^x. In order to produce a ggplot graph, I have to do the following:

x <- 1:20

a <- 0.5^x

b <- 0.8^x

data.frame(x, a, b) %>% 
  pivot_longer(c(a, b)) %>% 
  ggplot(aes(x = x, y = value, color = name, group = name)) 
  geom_line()

Output:

enter image description here

Which completely doesn't correspond to the psychological process in my head to create such a graph - mainly becasue of converting it to the long format to be able to group it.

In my head, I am creating two simple, but distinct curves on the same canvas. So I should be able to use something like:

qplot(x, 0.5^x, geom = "line") 
qplot(x, 0.8^x, geom = "line")

However, that doesn't work because

Can't add `qplot(x, 0.8^x, geom = "line")` to a ggplot object.

Any help with how to create such a simple graph without reshaping the data would be appreciated, thanks.

CodePudding user response:

Using geom_function you could do:

library(ggplot2)

ggplot()  
  geom_function(fun = ~ 0.5^.x, mapping = aes(color = "a"))  
  geom_function(fun = ~ 0.8^.x, mapping = aes(color = "b"))  
  xlim(1, 20)

Created on 2022-05-08 by the enter image description here

  • Related