[R] Limit the y-axis line with ggplot2 (not the axis itself, but the line used at the left of the graph)
Zach Simpson
zpsimpso at gmail.com
Wed Oct 26 00:40:48 CEST 2016
> Hello everybody,
>
> Using ggplot2 package, is there a way to force to stop the y-axis line
> at a specified point ? (not using ylim because I want that some text
> written using annotate() at the top of the graph is still shown).
>
> Bellow is a simple example to show what I would like do:
>
> Thanks a lot
>
> Marc
>
>
>
>
>
> library("ggplot2")
>
> g <- ggplot()+
> geom_point(aes(x=c(20, 29, 32), y=c(0, 0.4, 1)))+
> scale_y_continuous(breaks=c(0, 0.25, 0.5, 0.75, 1))+
> labs(x="Label for x axis")+
> labs(y="Label for y axis") +
> annotate("text", x = 25 , y=1.2, label="Text 1")+
> annotate("text", x = 22 , y=1.0, label="How to stop the y-axis line
> here !")+
> geom_segment(aes(x=25, xend=25, y=0, yend=1.1), linetype=2)+
> > This part is just to make it more nice
> theme(panel.background = element_rect(fill = 'white'),
> panel.grid.major = element_blank(),
> panel.grid.minor = element_blank(),
> plot.margin = unit(c(0.5, 1, 0.5, 0.5), "cm"),
> axis.text.x=element_text(size=14),
> axis.text.y=element_text(size=14),
> axis.title.x=element_text(size=18),
> axis.title.y=element_text(size=18),
> axis.ticks.length=unit(0.3,"cm"),
> panel.border = element_blank(),
> axis.line.x = element_line(),
> axis.line.y = element_line())
> g
Hey Marc,
I feel there's a better solution out there, but I think I got what
you're after by replacing the y-axis with a
`annotate(geom="segment")`, which I could manipulate using the y and
yend arguments.
It took some other finagling of the other elements though.
#after already defining g per the OP
g + scale_x_continuous(limits = c(19,32.5), expand = c(0,0)) +
scale_y_continuous(limits=c(-0.05,1.25), breaks=c(0, 0.25, 0.5,
0.75, 1), expand = c(0,0))+
annotate(geom = "segment", x=19, xend = 19, y = -0.05, yend = 1)+
theme(axis.line.y = element_blank())
Cheers,
Zach
More information about the R-help
mailing list