0

I want to automatically set the number of breaks and the position of the breaks itself for the axis of a discrete variable such that the labels which are plotted are actually readable.

For example in the code below, the resulting plot should only show a portion of the labels/the x-variable.

ggData <- data.frame(x=paste0('B',1:100), y=rnorm(100))
ggplot(ggData, aes_string('x', 'y')) +
   geom_point(size=2.5, shape=19, na.rm = TRUE) 

enter image description here

So far, I tried to use pretty, and pretty_breaks which are, however, not for discrete variables.

mpalanco
  • 12,960
  • 2
  • 59
  • 67
Nussig
  • 291
  • 1
  • 8
  • for reference http://www.cookbook-r.com/Graphs/Axes_(ggplot2)/ – Pierre L Sep 02 '15 at 19:04
  • Thank you for the reference. However, I do not think any of the examples discussed there provides a solution to the problem above. – Nussig Sep 02 '15 at 19:39
  • 1
    Maybe you want to make a function for breaks a la [this answer](http://stackoverflow.com/a/19512630/2461552)? I don't know how you will decide how many breaks you want, but something along the lines of, e.g., `scale_x_discrete(breaks= function(n) n[seq(0, length(n), by = length(n)/10)])` would be somewhat automatic. – aosmith Sep 02 '15 at 20:45

1 Answers1

2

Fist we turn the factor into a character and then into a ordered factor. Secondly, we subset ggData$x to create a vector (labels) with the ticks we want. In the example every 10 elements. Finally, we create the plot using scale_x_discrete, using the previous vector (labels), inside the parameter breaks.

ggData <- data.frame(x=paste0('B',1:100), y=rnorm(100))
ggData$x <- as.character(ggData$x)
ggData$x <- factor(ggData$x, levels=unique(ggData$x))
labels <- ggData$x[seq(0, 100, by= 10)]

ggplot(ggData, aes_string('x', 'y')) +
  geom_point(size=2.5, shape=19, na.rm = TRUE)  +
scale_x_discrete(breaks=labels)

enter image description here

mpalanco
  • 12,960
  • 2
  • 59
  • 67
  • Thanks for the advice. I eventually solved it using your suggestion in combination with the `pretty_breaks` function from the `scales` package. – Nussig Sep 04 '15 at 18:12