0
ggplot(jw, aes(n, prob)) +
  geom_line() +
  geom_hline(yintercept = mean(jw$prob), colour = 'red') +
  geom_point(colour = 'blue')

Gives: Plot 1

ggplot(jw, aes(n, prob)) +
  geom_line() +
  geom_hline(yintercept = mean(jw$prob), colour = 'red') +
  scale_y_continuous(breaks = c(pretty(jw$prob), mean(jw$prob))) +
  geom_point(colour = 'blue')

Gives: Plot 2

I am looking for certain features from both. I would like to keep the y-axis values at 1.d.p from the first plot, but keep the decimal places of the horizontal line value, or ideally rounding it to 6.d.p. I would also like to change the colour of the hline value to red so it matches the line.

The second plot has introduced some strange grid lines that were not there before as well, it would be nice if it was like the first plot.

At the moment the horizontal line value is not interfering with the y-value of 0.2, but if it was a little higher there would be some overlap and it would look messy. Is there a way to create a small bubble round it or something like that so if the two values get in the way of each other the hline value is over the top and can be clearly read?

EDIT:

Thanks for the suggestions, I have been playing around with it and have got the result I was looking for. The only slight downside now is that I have had to tell it which number of axis tick I want red, instead of assigning it to the mean, wherever it may fall on the axis. So if the mean value falls between two other ticks, the code will assign some other tick to red. I'm still confused as to why it messes up the grid lines as well.

So,

ggplot(jw, aes(n, prob)) +
  geom_line() +
  geom_hline(yintercept = mean(jw$prob), colour = 'red') +
  scale_y_continuous(breaks = sort(c(pretty(jw$prob), mean(jw$prob))),
                     labels = sort(c('0', '0.1', '0.2', '0.3', '0.4',
                                     round(mean(jw$prob), digits = 6)))) +
  theme(axis.text.y = element_text(colour = c('black', 'black', 'red',
                                              'black', 'black', 'black'))) +
  geom_point(colour = 'blue')

Gives: Plot 3

85sph
  • 61
  • 4
  • You might be better off using `annotate` than fiddling with the scale. See for example http://stackoverflow.com/questions/36804354/ggplot2-annotate-y-axis-to-indicate-direction-of-scale-used – Richard Telford Feb 11 '17 at 22:43
  • 1
    Set the `labels` to character versions of the `breaks` formatted as you like. You should [make your example reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610), though. – alistaire Feb 11 '17 at 23:09

0 Answers0