geom_smooth with string in R

Viewed 141

I have a variable I want to use for the y-axis in ggplots, which must be passed as its "" name (for reasons like, I could use a few variables there and want a changing y-axis label to reflect it).

But I also want to plot a smoothed line on the graph.

ggplot(data=iris, aes(x=Sepal.Width, col=Species)) +
  geom_point(aes_string(y="Petal.Length")) +
  geom_smooth(method="lm", formula=y~x, se=F)

gives Error: stat_smooth requires the following missing aesthetics: y. Is there any way of doing it?

1 Answers

Are you looking for help('get')? It will

Return the Value of a Named Object

and use it as the y coordinate to plot the data.

library(ggplot2)

ggplot(data=iris, aes(x=Sepal.Width, y = get("Petal.Length"), color=Species)) +
  geom_point() +
  geom_smooth(method="lm", formula=y~x, se=F)

enter image description here

Related