Using this code as example:
df <- data.frame(
x = c(30, 40, 20, 60)
, y = c(10, 20, 5, 70)
, group = c("g1", "g1", "g2", "g2")
)
options(repr.plot.width = 10, repr.plot.height = 7)
ggplot()
geom_point(data=df, aes(x=x, y=y, group=group, color=group))
geom_step(data=df, aes(x=x, y=y, group=group, color=group), size=1)
scale_y_continuous(breaks = round(seq(0, 100, by = 5), 1))
coord_cartesian(ylim = c(0, 100))
It produces:
Is there an easy way in ggplot (?) to achieve the following (only indicated by one step function):
Or do I need to change original data and somehow impute? Hope this makes sense? Thanks!
CodePudding user response:
You could add rows for each group's starting and ending points to match the desired result:
df <- df %>%
group_by(group) %>%
group_modify(~ add_row(.x, x=c(0, Inf), y=c(0, max(.x$y))))
# group x y
# <chr> <dbl> <dbl>
#1 g1 30 10
#2 g1 40 20
#3 g1 0 0
#4 g1 Inf 20
#5 g2 20 5
#6 g2 60 70
#7 g2 0 0
#8 g2 Inf 70
ggplot(df, aes(x=x, y=y, group=group, color=group))
geom_point()
geom_step(size=1)
scale_y_continuous(breaks = round(seq(0, 100, by = 5), 1))
coord_cartesian(ylim = c(0, 100), xlim = c(20,60))
Or, if you want this only for the first group (same idea; but not by group):
df %>%
add_row(., group = "g1", x = c(0, Inf), y = c(0, max(.$y[.$group == "g1"]))) %>%
ggplot(aes(x=x, y=y, group=group, color=group))
geom_point()
geom_step(size=1)
scale_y_continuous(breaks = round(seq(0, 100, by = 5), 1))
coord_cartesian(ylim = c(0, 100), xlim = c(20,60))
CodePudding user response:
Hope I get your question right.
You don't really need to "impute" anything, because what you want is to extend the geom_step() to 0 on the left hand side and Inf on the right hand side. So I added the corresponding values in df.
df <- data.frame(
x = c(30, 40, 20, 60, Inf, -Inf),
y = c(10, 20, 5, 70, 20, 0),
group = c("g1", "g1", "g2", "g2", "g1", "g1")
)
ggplot()
geom_point(data=df, aes(x=x, y=y, group=group, color=group))
geom_step(data=df, aes(x=x, y=y, group=group, color=group), size=1)
scale_y_continuous(breaks = round(seq(0, 100, by = 5), 1))
coord_cartesian(ylim = c(0, 100))





