Reputation: 323
I have a data frame with 3 columns. I am plotting a factor (X) by a numeric variable (Prob). I would like to draw a line from each point down to the y=0 line. I tried to do this with the code below after reading this post R ggplot vertical and horizontal line intercept at center. The results were not what I expected. I think this may have to do with the fact that my x-axis variable is a factor. Is there a better way that I can do this?
pmf.data = as.data.frame(c(0,1,2,"NA"))
pmf.data$Prob = c(0.4921875, 0.015625, 0.4921875, 0)
colnames(pmf.data)[1] = c("X")
pmf.data$label = c("P0", "P1", "P2", "PNA")
ggplot(data=pmf.data, aes(x=X, y=Prob)) + geom_point() +
geom_text(aes(label = label), hjust = 2) +
geom_segment(aes(xend=Prob, yend=0), color="blue") +
ylab(expression(bold(paste(f[(X)](x))))) +
ggtitle("Multinomial pdf for X")
Upvotes: 1
Views: 4777
Reputation: 98599
If you need a vertical line that goes to y=0 then xend=
values inside the geom_segment()
should be the same as x value - that is - X
.
ggplot(data=pmf.data, aes(x=X, y=Prob)) + geom_point() +
geom_text(aes(label = label), hjust = 2) +
geom_segment(aes(xend=X, yend=0), color="blue") +
ylab(expression(bold(paste(f[(X)](x))))) +
ggtitle("Multinomial pdf for X")
The same effect as with geom_segment()
can be atchieved with geom_bar()
and setting width=
some low value.
ggplot(data=pmf.data, aes(x=X, y=Prob))+geom_bar(stat="identity",width=0.01)
Upvotes: 3