tumultous_rooster
tumultous_rooster

Reputation: 12570

creating a single colored point over a normal distribution in ggplot

I was looking to plot a normal distribution in ggplot, and at the suggestion of @nrussell I have used

ggplot(data.frame(x = c(-5, 5)), aes(x)) + stat_function(fun = dnorm)

enter image description here

I am wondering if there is any way to, within the context of stat_function, layer a single colored point directly onto the curve. For example, if I wanted to put a dot where the x axis is marked 2.

I have experimented with geom_point but this appears to be better at creating scatterplots: I can't seem to pipe in the aesthetics from the stat_function for the layer be created.

Any advice would be greatly appreciated.

Upvotes: 2

Views: 2415

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 146090

Use annotate, and just specify x = 2, y = dnorm(2). Rather than trying to pull info out of stat_function()

ggplot(data.frame(x = c(-5, 5)), aes(x)) +
  stat_function(fun = dnorm) +
  annotate(geom = "point", x = 2, y = dnorm(2), color = "red")

Annotate is best for small additions. To use geom_point() you'd want to define a new data.frame, good if you wanted to plot more than one point.

Upvotes: 2

nrussell
nrussell

Reputation: 18612

There may be a way to do this with another stat_function layer, but after playing around with it for a few minutes it seemed easier to just use geom_point to add a single point:

library(ggplot2)
##
ggplot(
  data.frame(x = c(-5, 5)), 
  aes(x))+ 
  stat_function(fun = dnorm)+
  geom_point(
    data=data.frame(x=2,y=dnorm(2)),
    aes(x,y),
    color="red",
    size=4)
##

enter image description here

Upvotes: 3

Related Questions