Rajan
Rajan

Reputation: 463

box plot in R with additional point

I have a dataframe of multiple columns (let's say n) with different range and a vector of length n. I want different x-axis for each variable to be shown below each box plot. I tried facet_grid and facet_wrap but it gives common x axis. This is what I have tried:

d <- data.frame(matrix(rnorm(10000), ncol = 20))

point_var <- rnorm(20)
plot.data <- gather(d, variable, value)
plot.data$test_data <- rep(point_var, each = nrow(d))

ggplot(plot.data, aes(x=variable, y=value)) + 
geom_boxplot()  + 
geom_point(aes(x=factor(variable), y = test_data), color = "red") + 
coord_flip() + 
xlab("Variables") + 
theme(legend.position="none") 

Upvotes: 0

Views: 139

Answers (1)

lbusett
lbusett

Reputation: 5932

If you can live with having the text of the x axis above the plot, and having the order of the graphs a bit messed-up this could work:

library(grid)
p = ggplot(plot.data, aes(x = 0,  y=value)) + 
  geom_boxplot()  + 
  geom_point(aes(x = 0, y = test_data), color = "red") + 
  facet_wrap(~variable, scales = "free_y", switch = "y") +
  xlab("Variables") +
  theme(legend.position="none") + theme_bw() + theme(axis.text.x=element_blank())

  print(p, vp=viewport(angle=270,  width = unit(.75, "npc"), height = unit(.75, "npc")))

I'm actually just creating the graph without flipping coords, so that scales = 'free_y' works, swithcing the position of the strip labels, and then rotating the graph.

If you don't like the text above graph (which is understandable), I would consider creating a list of single plots and then putting them together with grid.arrange.

HTH,

Lorenzo

Upvotes: 1

Related Questions