Skip to content

Instantly share code, notes, and snippets.

@romunov
Created February 10, 2021 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romunov/b4da5124d022c112defc24799fe96e2c to your computer and use it in GitHub Desktop.
Save romunov/b4da5124d022c112defc24799fe96e2c to your computer and use it in GitHub Desktop.
plot a funny function with X in exponent with ggplot2
naloga <-data.frame("U308"=c(8.23, 8.78, 9.90, 10.90, 17.88, 29.00, 44.17, 83.01))
naloga$Leto <- seq(from=2000, to=1999+length(naloga$U308))
fit <- lm(log(U308) ~ Leto, data=naloga)
ggplot(naloga, aes(x = Leto, y = U308)) +
geom_point() +
ylab("Cena funta urana U308 v $") +
geom_function(fun = function(x) exp(coef(fit)[1]) * (exp(coef(fit)[2])^(x)), col="black", lty=2, size=0.3)
@romunov
Copy link
Author

romunov commented Feb 10, 2021

image

@romunov
Copy link
Author

romunov commented Feb 10, 2021

It's super easy to predict new values in time..

newdata <- data.frame(Leto = c(2008, 2011, 2021))
newdata$U308 <- predict(fit, newdata = newdata)
newdata$U308 <- exp(newdata$U308)

ggplot(naloga, aes(x = Leto, y = U308)) +
  geom_point() +
  scale_x_continuous(limits = c(2000, 2021)) +
  ylab("Cena funta urana U308 v $") +
  geom_function(fun = function(x) exp(coef(fit)[1]) * (exp(coef(fit)[2])^(x)), col="black", lty=2, size=0.3) +
  geom_point(data = newdata, color = "red")

image

@romunov
Copy link
Author

romunov commented Feb 10, 2021

To map models to a legend, you can do

mdl.lin <- lm(U308 ~ Leto, data = naloga)
mdl.log <- lm(log(U308) ~ Leto, data = naloga)

fits <- data.frame(Leto = seq(from = 2000, to = 2021, by = 0.1))
fit.lin <- fits
fit.log <- fits

fit.lin$fit <- predict(mdl.lin, newdata = fits)
fit.lin$method = "linear"

fit.log$fit <- predict(mdl.log, newdata = fits)
fit.log$fit <- exp(fit.log$fit)
fit.log$method = "log"

fits <- rbind(fit.lin, fit.log)

ggplot(naloga, aes(x = Leto, y = U308)) +
  geom_point() +
  scale_x_continuous(limits = c(2000, 2021)) +
  scale_color_brewer(palette = "Set1") +
  ylab("Cena funta urana U308 v $") +
  geom_line(data = fits, aes(x = Leto, y = fit, color = method))

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment