r - Remove unnecessary y-axis points with facet_wrap and geom_segment -
i'm mapping y-axis points x-axis using geom_segment()
, using facet_wrap
separate data 2 plots; however, y-axis points showing on both plots.
how can have necessary y-axis points pertaining each facet_wrap
?
sample code
dat <- structure(list(temp = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5), rev = c(-5, -11, -20, -29, -40, -9, -20, -32, -45, -57, -12, -24, -37, -50, -62, -7, -20, -36, -52, -67, -5, -13, -23, -35, -47, -12, -24, -36, -48, -58), type = c("type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 1", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2", "type 2"), model = c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c")), .names = c("temp", "rev", "type", "model"), row.names = c(na, -30l), class = "data.frame") p1 <- ggplot(dat, aes(temp, rev, color = model)) + geom_line() + geom_point() + geom_segment(aes(x = 0, xend = temp, yend = rev), linetype = "dashed", color = "grey") + facet_wrap(~type, scales = "free") + scale_y_continuous(breaks = dat$rev) p1
plot
i made dummy data because reason pasting dput
console made unhappy.
library(dplyr) df <- expand.grid(temp = 1:5, model = letters[1:3], type = 1:2) %>% group_by(model, type) %>% mutate(rev = -sort(sample.int(20, length(temp)))) # equivalent data as-is, structurewise
df.labeled <- df %>% ungroup() %>% group_by(type, rev) %>% mutate(label = c(rev[1], rep(na, length(rev) - 1)))
here created group each y value shows in each group panel. create label
column consists of 1 observation of y value, padded na
s. if panel have had 2 models each had rev
of -5
, -5, na
instead of -5, -5
. why i'm doing become clearer below.
ggplot(df.labeled, aes(temp, rev, color = model)) + geom_segment(aes(xend = 0, yend = rev), linetype = "dashed", color = "grey") + geom_text(aes(label = label, x = -0.1), colour = "black", hjust = 1) + geom_vline(xintercept = 0) + geom_point() + geom_line() + facet_grid(~type) + scale_y_continuous(breaks = null) + scale_x_continuous(limits = c(-0.5, na)) + theme_bw() + theme(panel.grid = element_blank())
if had left in duplicates (here have been -7, -15 type 1 , -11 type 2), geom_text
have been messy bolded blur. duplicated text labels don't render in ggplot2
. since it's not possible way wanted, here we're making fake scale each panel. if don't fact there's line on y-axis left of numbers, can gotten rid of:
... + theme(panel.grid = element_blank(), panel.border = element_blank(), axis.line.x = element_line())
Comments
Post a Comment