1

when using this code:

t1 <- ggplot(mtcars, aes(x=as.factor(cyl),y=mpg))
t2 <- geom_boxplot(outlier.shape=NA)
t3 <- geom_jitter(width=0.3, size=1.5, aes(color = disp))
t4 <- scale_colour_gradient(low="blue",high="red")
t5 <- geom_text(aes(label=ifelse(mpg > 30,as.character(mpg),'')))

t1 + t2 + t3 + t4 + t5

I get a boxplot in combination with jitter points. I am also able to label the points of interest, however: the labeling is not next to the specific point, but rather in the vertical middle of the boxplot.

Here is the figure

Any idea how I can place the text next to the corresponding point?

Thank you a lot guys!

By the way: can you recommend me a course or a tutorial for ggplot2 beginners?

choco.latte
  • 35
  • 1
  • 5
  • 1
    This topic must give you some hints: http://stackoverflow.com/questions/6551147/adding-text-to-ggplot-geom-jitter-points-that-match-a-condition – bVa Apr 27 '16 at 07:26
  • I have a question on you choice of plot. How should one read the horizontal jittering of points given that the x-axis is a factor with 4,6 and 8 as the only unique values? Just curious!1 – Gaurav Taneja Apr 27 '16 at 09:29

1 Answers1

2

Jitter it beforehand?

library(ggplot2)
set.seed(1)
t1 <- ggplot(transform(mtcars, xjit=jitter(as.numeric(as.factor(cyl)))), aes(x=as.factor(cyl),y=mpg))
t2 <- geom_boxplot(outlier.shape=NA)
t3 <- geom_point(size=1.5, aes(x=xjit, color = disp))
t4 <- scale_colour_gradient(low="blue",high="red")
t5 <- geom_text(aes(x=xjit, label=ifelse(mpg > 30,as.character(mpg),'')), vjust = 1)

t1 + t2 + t3 + t4 + t5

enter image description here

lukeA
  • 53,097
  • 5
  • 97
  • 100
  • Thank you lukeA. As I still consider myself as a beginner in R, I have to ask you about some changes in the code you made. Can you please tell me why you used transform in the t1 line, and what is transform doing acutally to the remaining code? I also do not understand what xjit is, and what in the t3 line color = disp does (what is disp)? Sorry for all the questions... – choco.latte Apr 27 '16 at 08:46
  • 1
    Sure. I used `transform` to create a new column `xjit` on the fly, i.e. just for the plot, without storing another variable somewhere in the R environment. `xjit` is the _jit_'tered _x_-value. `color=disp` comes from your example - it maps the column `disp` to the color aesthetics. – lukeA Apr 27 '16 at 09:23