如何将此ggplot2条形图转换为线图?

时间:2013-08-27 21:48:43

标签: r ggplot2

我的数据集在x轴上具有离散的有序因子。我想将渲染从条形图更改为折线图(采用geom_freqpoly的样式)。我无法直接使用geom_freqpoly,因为我已经汇总了我的数据,而且我不知道如何将统计信息从stat = "bin"更改为stat = "identity"。我怎样才能做到这一点?

以下是数据:

temp <- structure(list(wday = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 
4L, 5L, 5L, 6L, 6L, 7L, 7L), .Label = c("Monday", "Tuesday", 
"Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), class = c("ordered", 
"factor")), splitter = c(FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, 
FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE), N = c(250245, 
40845, 209685, 45946, 200983, 49403, 142869, 52212, 88589, 48175, 
51061, 25317, 84012, 7994), price1 = c(22.79, 70.20, 35.92, 87.66, 
48.98, 55.37, 22.56, 88.50, 26.12, 63.29, 35.88, 73.79, 33.12, 82.80
)), .Names = c("wday", "splitter", "N", "price1"), class = "data.frame", 
row.names = c(NA, -14L))

这是情节:

ggplot(melt(temp,id.vars = c("wday","splitter")), 
  aes(x = wday, y = value, fill = splitter)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  facet_grid(variable ~ ., scale = "free_y")

虽然我认为以下代码可行,但它不会:

ggplot(melt(temp,id.vars = c("wday","splitter")), 
  aes(x = wday, y = value, colour = splitter)) + 
  geom_point() + geom_line() +
  facet_grid(variable ~ ., scale = "free_y")

1 个答案:

答案 0 :(得分:3)

这个问题是一个缺失的群体美学。函数geom_line使用因子作为默认分组变量(此处为wdaysplitter),因此每个组都是单个数据点。在aes中指定分组会根据需要呈现行:

ggplot(melt(temp,id.vars = c("wday","splitter")), 
  aes(x = wday, y = value, colour = splitter, group = splitter)) + 
  geom_point() + geom_line() +
  facet_grid(variable ~ ., scale = "free_y")

Now with lines!