person
person

Reputation: 96

Create discrete bins on continuous x axis with ggplot

I have found similar questions but unfortunately none that have helped me solve this problem.

I want to replace my continuous x axis labels according to a factor using ggplots.

With some help from SO, the image below is as close as I have been able to come. It is almost right, however I would like to remove the zero on the far left of the x axis and center the rest of the labels on the x axis in their respective bins.

nearly_there

The code used to generate this is:

library(ggplot)

test_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=TRUE),
       scale_x_continuous(breaks=c(0,4,8,10), labels =c("0","a","b","c")))
}

test_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=TRUE),
       scale_y_continuous(breaks=b))
}


test <- data.frame(names=c("a","a","a","a","b","b","b","b","c","c"),position=c(1,2,3,4,5,6,7,8,9,10),value=c(10,12,14,12,6,7,7,5,18,20))
test_plot <- ggplot(test, aes(position,value))
test_plot <- test_plot +geom_line()
test_plot <- test_plot + test_base_breaks_x(test$position)
test_plot <- test_plot + test_base_breaks_y(test$value)
jpeg("test.jpg")
test_plot
dev.off()

Thanks in advance for your help!

Upvotes: 0

Views: 1681

Answers (1)

B Williams
B Williams

Reputation: 2050

Might I recommend a slightly different approach

library(tidyverse)
data.frame(names=c("a","a","a","a","b","b","b","b","c","c"),
        position=c(1,2,3,4,5,6,7,8,9,10),
        value=c(10,12,14,12,6,7,7,5,18,20)) -> test

First you can do a basic figure plot

test %>% 
  ggplot(aes(position, value)) + geom_line()

Then add color to show your groups

test %>% 
  ggplot(aes(position, value, color = names)) + geom_line()

Make them a single group to connect the line

test %>% 
  ggplot(aes(position, value, color = names, group = 1)) + geom_line()

Now you can change the location of your breaks and labels easily. The mid point of group "a" is 3, group "b" is 6.5, etc.

test %>% 
  ggplot(aes(position, value, color = names, group = 1)) + geom_line() +
  scale_x_continuous(breaks = c(3, 6.5, 9))

Now change the labels

test %>% 
  ggplot(aes(position, value, color = names, group = 1)) + geom_line() +
  scale_x_continuous(breaks = c(3, 6.5, 9), labels = c('a', 'b', 'c'))

The you can remove the color if desired

test %>% 
  ggplot(aes(position, value)) + geom_line() +
  scale_x_continuous(breaks = c(3, 6.5, 9), labels = c('a', 'b', 'c'))

Upvotes: 2

Related Questions