0

I have a simple table:

# A tibble: 6 × 2
  weekday  total_cal
  <chr>        <dbl>
1 Friday       2220.
2 Monday       2104.
3 Saturday     2205.
4 Sunday       2070.
5 Thursday     1930.
6 Tuesday      2152.

After which, I create this bar chart:

calories_weekday_avg %>% 
  ggplot(aes(x = weekday, y = total_cal))+
  geom_bar(stat = "identity", width = 0.75)+
  scale_x_discrete(limits = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))

I want the y-axis to start at 1000 instead of 0, so when I add in that code via the scale_y_continous function, it works, but my bars disappear entirely:

calories_weekday_avg %>% 
  ggplot(aes(x = weekday, y = total_cal))+
  geom_bar(stat = "identity", width = 0.75)+
  scale_x_discrete(limits = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))+
  scale_y_continuous(limits = c(1000, 2300))

Where I am missing something? I've done this before but somehow it worked then.

Phil
  • 7,287
  • 3
  • 36
  • 66
  • If you want to only show data that falls within your specified range, and exclude other data, use `scale_y_continuous(limits = ...)`. If you want to show all data but "zoom in," use `coord_cartesian(ylim = ...)` – Jon Spring Feb 03 '23 at 03:41
  • Great thanks! The coord_cartesian worked well. I still don't know why the scale_y_continuous didn't work, because none of my data was outside the range that I set for the y-axis. Sure, the actual bar itself has to start from 0 and go up to a specific data point, but all my data points were still within the range that I set. At least the coord function worked. Thanks. – shahanimal Feb 03 '23 at 19:38
  • I think from ggplot2's perspective, the bars are represented as a range from 0 to your y value, so if you use `scale_y_continuous` to exclude data below 1000, that will exclude some of each bar, so all the bars will be excluded. `coord_cartesian` is made to work differently, so it will show "zoomed" in data even if some of the objects in the view frame are partly obscured. This difference of behavior was intentional but it is often not what people expect, unfortunately. – Jon Spring Feb 03 '23 at 20:49

0 Answers0