'ggplot - is it at all possible to draw multiple lines without grouping data

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.



Solution 1:[1]

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 reprex package (v2.0.1)

Solution 2:[2]

Maybe something like this. It is possible to keep the data in wide format. But generally it is better to bring it long foramt:

library(ggplot2)

ggplot()+
  geom_line(aes(x, 0.5^x, color="red"))+
  geom_line(aes(x, 0.8^x, color = "blue"))+
  scale_color_identity()         

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stefan
Solution 2