0

I am attempting to use seq() to define my breaks on a plot. Dummy example below.

ggplot(data, aes(x=cat, y=dog) +
    scale_y_continuous(breaks=seq(-0.3, 0.3, by=0.1))

For some reason, seq() is giving me output numbers that are off by minute amounts. This behavior occurs within and outside of my plotting device. As evidenced below, it appears to be a problem with generating negative numbers. It can produce them, but that's where the issue appears.

seq(0.3, 0.9, by=0.1)  # test with positives
seq(-0.3, 0.3, by = 0.1)  # test with negatives
format(seq(-0.3, 0.3, by = 0.1), scientific = F)  # show full number

enter image description here

I read the documentation and couldn't find anything talking about negatives so I'm not sure how to fix it. Is there something I'm doing wrong or excluding? Is there a workaround or another function I should be using?

edit Marked as duplicate but the duplicate doesn't explicitly provide a solution to this. Here's a few:

# i went with this solution as given in comments to keep it all contained within seq()
seq(-0.3, 0.3, length.out=7) 

# from the answers
seq(-3, 3, by=1)/10

# didn't work for my case but should work as a general rule
round(x, digits=n)  # x would be the seq(-0.3, 0.3, by = 0.1) and n=1 in my case)
cparmstrong
  • 799
  • 6
  • 23
  • 1
    Since the question was marked as a duplicate I can't submit this as an answer. From ?seq: 'Specifying to - from and by of opposite signs is an error.' As for a workaround, it seems to be fine if you do seq(from = -0.3, to = 0.3, length.out = 7) – jpshanno Oct 19 '17 at 16:21
  • @jpshanno 0.3 - (-0.3) = 0.6 That's the same sign as 0.1. No, this is just the usual floating point numbers FAQ. – Roland Oct 19 '17 at 16:26
  • 1
    @Roland, I don't think the question you linked to answers this question. This question is asking how to get seq() to give the expected output when from and to are opposite signs, not why aren't the numbers equal. – jpshanno Oct 19 '17 at 16:26
  • If you understand the issue you'll know that you simply need to round. – Roland Oct 19 '17 at 16:28
  • Thanks @jpshanno, your solution with `length.out`. The 'duplicate' provided useful insight but not quite a clear path forward for me. I had already tried round(seq(x, 2)) which failed which is what brought me here. – cparmstrong Oct 19 '17 at 16:31
  • I did misread the help as 'to, from, and by', not 'to - from and by' – jpshanno Oct 19 '17 at 16:39

1 Answers1

1

For a workaround you could try seq(-3,3,1)/10

loukdelouk
  • 78
  • 4
  • Your solution works. I chose to go with @jpshanno's because it keeps it contained within seq but as it had already been marked duplicate I couldn't give him the check so it's all yours. – cparmstrong Oct 19 '17 at 16:33