creating a single colored point over a normal distribution in ggplot

怎甘沉沦 提交于 2019-12-06 12:06:55

问题


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)

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.


回答1:


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)
##




回答2:


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.



来源:https://stackoverflow.com/questions/26683698/creating-a-single-colored-point-over-a-normal-distribution-in-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!