I am trying to add geom_text labels to my mosaic plot below:
that I generated using ggplot2 with the code below:
tsc.p1 <- tsc.p + geom_rect(colour = I("grey")) +
facet_grid(helmet~.) +
geom_text(aes(x = c(9.0, 22.0, 33.0, 46.0, 72.0, 98.0),
y = 125,
label = c("C", "DS", "S", "ST", "Std", "T")),
size = 3) +
scale_fill_brewer(palette = "Greys") +
xlab("Percentage of Sample") +
ylab("Percentage Responded") +
opts(title="Mosaic Plot of Helmet Type Use",
legend.position="none") +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 125)) +
ylim(0, 101)
I ha开发者_JAVA百科ve two problems:
- The ylim cuts off my geom_text at the top.
- Without the ylim() function, the first three categories are shown above the odd numbered facets, and the last three categories are shown above the even numbered facets, counting from the top-most facet. I couldn't figure out how or why this is the case.
I only want to add the six categories to the top of the plot. Is there a way to do this?
As Andrie says it's hard to test with out data. But you want to use coord_cartesian limits for your first questinion, as scale limits throws away data that's out it range. Here's my solution, I merged the labs and the scales because sometimes they can collide.
tsc.p1 <- tsc.p + geom_rect(colour = I("grey")) +
facet_grid(helmet~.) +
geom_text(aes(x = c(9.0, 22.0, 33.0, 46.0, 72.0, 98.0),
y = 125,
label = c("C", "DS", "S", "ST", "Std", "T")),
size = 3) +
scale_fill_brewer(palette = "Greys") +
opts(title="Mosaic Plot of Helmet Type Use",
legend.position="none") +
scale_x_continuous("Percentage of Sample", expand = c(0, 0)) +
scale_y_continuous("Percentage Responded", expand = c(0, 125)) +
cood_cartesian(ylim = c(0, 101))
HTH
I got what I wanted by just splitting up the geom_text in half and having two functions. I don't know why this works, but it does!
tsc.p <- ggplot(tsc,
aes(ymin = ymin, ymax = ymax,
xmin = xmin, xmax = xmax,
fill = variable))
tsc.p1 <- tsc.p + geom_rect(colour = I("grey")) +
facet_grid(helmet~.) +
geom_text(aes(x = c(9.0, 22.0, 33.0),
y = 25,
label = ifelse(helmet == "FF",
c("Cru", "DualSp", "Sport"),
"")),
size = 3) +
geom_text(aes(x = c(45.0, 72.0, 97.0),
y = 25,
label = ifelse(helmet == "FF",
c("SptTour", "Std", "Tour"),
"")),
size = 3) +
scale_fill_brewer("Frequency of Helmet Use", palette = "Greys") +
xlab("Percentage of Sample") +
ylab("Percentage Responded") +
opts(title="Mosaic Plot of Helmet Use by Helmet Type") +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 101)) +
ylim(0, 101)
And the graph:
精彩评论