Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R-style axes with ggplot

Tags:

r

ggplot2

Using ggplot, is it possible to get "R-style" x/y axes that don't meet at the origin and that instead consist of two disconnected ranges, as in the following example?

enter image description here

The reason here is mainly to get ggplot plots to look consistent next to pure-R ones.

like image 898
Christian Avatar asked May 30 '12 01:05

Christian


People also ask

How do I change the y axis values in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

How do I change the graph theme in ggplot2?

As well as applying themes a plot at a time, you can change the default theme with theme_set() . For example, if you really hate the default grey background, run theme_set(theme_bw()) to use a white background for all plots. You're not limited to the themes built-in to ggplot2.

How do you add axis lines in R?

Adding axis to a Plot in R programming – axis () Function axis() function in R Language is to add axis to a plot. It takes side of the plot where axis is to be drawn as argument. Parameters: side: It defines the side of the plot the axis is to be drawn on possible values such as below, left, above, and right.

How do you split the y axis in R?

Methodn1: Break Y-Axis of Plot Using gap. plot() Function of plotrix Package. In this method break y-axis of the plot using the gap. plot() Function of plotrix Package, the user first needs to install and import the plotrix package to the working console of the R, further the user needs to call the gap.


1 Answers

Try this,

library(ggplot2)

d <- data.frame(x=1:10, y=rnorm(10))

base_breaks_x <- function(x){
  b <- pretty(x)
  d <- data.frame(y=-Inf, yend=-Inf, x=min(b), xend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_x_continuous(breaks=b))
}
base_breaks_y <- function(x){
  b <- pretty(x)
  d <- data.frame(x=-Inf, xend=-Inf, y=min(b), yend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_y_continuous(breaks=b))
}

ggplot(d, aes(x,y)) +
  geom_point() +
  theme_bw() +
  theme(panel.border = element_blank(),
       panel.grid.major = element_blank(),
       panel.grid.minor = element_blank()) +
  base_breaks_x(d$x) +
  base_breaks_y(d$y)

screenshot

Edit: a related issue has since been discussed in the ggtheme package, and potentially provides a cleaner solution (no need to provide the data explicitly to the breaks function).

like image 54
baptiste Avatar answered Sep 30 '22 03:09

baptiste