Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot ticks and numbers of y and x axes in a ggplot graph?

Tags:

plot

r

ggplot2

axis

I'm plotting a graph using ggplot. Here is the exemple with the ggplot package:

df <- data.frame(
  gp = factor(rep(letters[1:3], each = 10)),
  y = rnorm(30)
)
ds <- plyr::ddply(df, "gp", plyr::summarise, mean = mean(y), sd = sd(y))

ggplot(df, aes(gp, y)) +
  geom_point() +
  geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
  theme(    axis.text.y = element_text(hjust = 3),
            axis.text.x = element_text(vjust = 5),
            axis.ticks.length = unit(-0.25,
                                     "cm"), # length of the axis ticks

  )

Here is the output:

enter image description here

As you can see, the ticks are inside but the numbers for the y axis are terribly aligned and the ones on the X axis are overlapping the ticks.

So in the end I'd want the ticks inside the graph and the axis labels (the numbers) inside the ggplot graph. I've heard that we should use the margin tool, but I'm not sure how to specify margins inside the graph.

Edit: You can see how when using the margin function, the numbers are not aligned properly... enter image description here

like image 211
M. Beausoleil Avatar asked Dec 28 '17 20:12

M. Beausoleil


1 Answers

Maybe specifying margin within element_text using the margin function is what you are looking for?

ggplot(df, aes(gp, y)) +
  geom_point() +
  geom_point(data = ds, aes(y = mean), colour = 'red', size = 3) +
  theme(    axis.text.y = element_text(margin = margin(0,-.5,0,.5, unit = 'cm')),
            axis.text.x = element_text(vjust = 5, margin = margin(-0.5,0,0.5,0, unit = 'cm')),
            axis.ticks.length = unit(-0.25,
                                     "cm") , # length of the axis ticks

  ) + ylim(c(min(df$y)-.5,max(df$y)))

enter image description here

like image 87
jrlewi Avatar answered Nov 01 '22 14:11

jrlewi