0

I've run into an issue where I'm trying to create a bar chart and have the user adjust which data is visible via two variables in ylim. However some of the data I'm using has negative values, and whenever I try to use two negative values for ylim, all of my data is removed.

Here's a dummy chunk of code demonstrating the problem (where a and b would be the user-defined variables):

a <- -10
b <- -1

df2 <- data.frame(food = c("mac", "bread", "hot dog", "t-rav", "gogurt"), 
                  rating = c(-8, -4, 2, -3, 5))

ggplot(df2, aes(food, rating)) +
    geom_bar(stat = 'identity') +
    ylim(a, b)

blank graph from this code:

blank graph from this code

This will do exactly what I want for two positive values, one negative and one positive, or one negative and one zero. But two negative values causes a blank graph.

Anyone know what issue I'm running into and what the fix might be?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
gturns
  • 1
  • 1
  • 1
    https://stackoverflow.com/questions/63473030/how-to-plot-negative-numbers-from-small-to-large-value-using-geom-bar-in-ggplot2 – Ben Bolker Nov 09 '21 at 23:37
  • I don't think it's the negative values per se, but that they exclude zero. – C8H10N4O2 Nov 09 '21 at 23:41
  • 1
    Ahh okay, so don't use bars is the answer haha. Thanks! – gturns Nov 09 '21 at 23:42
  • 1
    I'm not sure I recommend this cropped visualization, since the relative size of the bars doesn't scale with the values, but below is how you could do it. – C8H10N4O2 Nov 09 '21 at 23:47
  • Does this answer your question? [geom\_bar bars not displaying when specifying ylim](https://stackoverflow.com/questions/10365167/geom-bar-bars-not-displaying-when-specifying-ylim) – tjebo Nov 10 '21 at 07:40

1 Answers1

2

Try coord_cartesian() so that you keep the geom (which requires y=0) but just limit your view of it.

library(ggplot2)
a <- -10
b <- -1

df2 <- data.frame(food = c("mac", "bread", "hot dog", "t-rav", "gogurt"), 
                  rating = c(-8, -4, 2, -3, 5))

ggplot(df2, aes(food, rating)) +
  geom_bar(stat = 'identity') +
  coord_cartesian(ylim=c(a,b))

enter image description here

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134