为什么我的ggplot2条形图显示的ylim最小值大于0?

时间:2015-09-16 20:18:11

标签: r ggplot2

我试图以1到5的比例绘制答案,我希望ggplot2中的情节范围从1到5.当我更改scale_y_continuous(limits = c(1, 5))时,数据消失了。任何想法如何解决这个问题(除了从我的值和重新标记中减去1的hack-y方式)?

可重复的例子:

dat <- structure(list(year = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L), .Label = c("2011", "2012", "2013", "2015"
), class = "factor"), variable = structure(c(1L, 1L, 1L, 1L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 
6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L), .Label = c("instructor.knowledge", 
"instructor.enthusiastic", "instructor.clear", "instructor.prepared", 
"instructor.feedback", "instructor.out.of.class", "class.dynamic"
), class = "factor"), value = c(5, 4.75, 5, 4.75, 5, 5, 4.85714285714286, 
4.75, 4.75, 4.75, 4.71428571428571, 3.75, 5, 4.75, 5, 4.5, 5, 
4.75, NA, 5, 5, 5, NA, 4.5, 5, 5, NA, 4.5)), row.names = c(NA, 
-28L), .Names = c("year", "variable", "value"), class = "data.frame")

library(ggplot2)
ggplot(dat, aes(x = variable, y = value, fill = year)) + 
  geom_bar(position = "dodge", stat = "identity") +
  scale_y_continuous(name = "Average score across all respondents",
                     limits = c(1, 5),  # fails
                     # limits = c(0, 5),  # succeeds
                     breaks = 1:5)

2 个答案:

答案 0 :(得分:4)

你只需要设置oob = rescale_none参数就可以了:

library(scales)
library(ggplot2)
ggplot(dat, aes(x = variable, y = value, fill = year)) + 
  geom_bar(position = "dodge", stat = "identity") +
  scale_y_continuous(name = "Average score across all respondents",
                     limits = c(1, 5),
                     oob = rescale_none) 

enter image description here

请务必附上scales oob = rescale_none的工具包。

答案 1 :(得分:3)

正如另一种选择,您的数据可能更容易理解为分面线图:

ggplot(dat, aes(x = year, y = value, group=1)) + 
  geom_point() +
  geom_line() +
  scale_y_continuous(name = "Average score across all respondents",
                     limits = c(1, 5),  # fails
                     # limits = c(0, 5),  # succeeds
                     breaks = 1:5) +
  facet_grid(. ~ variable)

enter image description here