[R] ggplot: add points selectively to curves

Michael Friendly friendly at yorku.ca
Wed Apr 2 16:43:23 CEST 2014


I'm working on an example of plotting predicted probabilities from a 
proportional odds model.
The steps below generate a data frame, plotdat, that I want to plot with 
ggplot.

library(MASS)
data("Arthritis", package="vcd")
arth.polr <- polr(Improved ~ Sex + Treatment + Age, data=Arthritis, 
Hess=TRUE)

# get predicted probs for categories of Improve
arth.fitp <- cbind(Arthritis,
                   predict(arth.polr, type="probs"))
head(arth.fitp)

# reshape probs to long
library(reshape2)
plotdat <- melt(arth.fitp,
                 id.vars = c("Sex", "Treatment", "Age", "Improved"),
                 measure.vars=c("None", "Some", "Marked"),
                 variable.name = "Level",
                 value.name = "Probability")
## view first few rows
head(plotdat)

 > head(plotdat)
    Sex Treatment Age Improved Level Probability
1 Male   Treated  27     Some  None   0.7326185
2 Male   Treated  29     None  None   0.7174048
3 Male   Treated  30     None  None   0.7096042
4 Male   Treated  32   Marked  None   0.6936286
5 Male   Treated  46   Marked  None   0.5702499
6 Male   Treated  58   Marked  None   0.4563432

In the plot step, I am plotting Probability vs. Age, stratified by 
Level, and faceted by
Sex and Treatment.  My question concerns the use of geom_point().
The call below plots 3 points for each case, one on each Level curve.


ggplot(plotdat, aes(x = Age, y = Probability, color = Level)) +
     geom_line(size=2.5) + theme_bw() + xlim(10,80) +
     geom_point(color="black", size=1.5) +
     facet_grid(Sex ~ Treatment,
                labeller = function(x, y) sprintf("%s = %s", x, y)
                )

Instead,
I want to plot only one point for each case, for the value of Level that 
corresponds
to the value of Improved in this data set.  Somehow, this involves something
like an aes() argument to geom_point(), with Level indexed by Improved, 
or some such.
How can I do this?

-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept. & Chair, Quantitative Methods
York University      Voice: 416 736-2100 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA




More information about the R-help mailing list