在总结R中的值之后在ggplot中绘制线图

时间:2017-05-29 08:46:56

标签: r ggplot2

Click to see dataFrame

我有一个数据框,如下图所示,现在我想绘制一个线图,显示小时为x轴,平均值(计数)为y,颜色为天。我试过了,但视觉出现了空白

Click to see how my plot came up (empty)

ggplot(data=temp,aes(hour,mean(count),color=days))+geom_line() # This is what I tried. 

我检查了融化功能,试图做到这一点,但无法弄清楚。

使用dput的Dataframe结构

structure(list(days = structure(c(2L, 2L, 6L, 7L, 2L, 5L, 4L), .Label = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
), class = "factor"), hour = structure(c(20L, 17L, 15L, 7L, 8L, 
10L, 7L), .Label = c("0", "1", "2", "3", "4", "5", "6", "7", 
"8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", 
"19", "20", "21", "22", "23"), class = "factor"), `mean(count)` = c(222.576923076923, 177.567307692308, 252.836538461538, 9.51428571428571, 184.922330097087, 161.480769230769, 68.3009708737864)), .Names = c("days", "hour", "mean(count)"), row.names = c(44L, 41L, 135L, 151L, 32L, 106L, 
79L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

带括号的列名是非标准变量名。因此,您需要使用反引号来引用该列。

此外,由于hour变量是一个因素,因此您需要使用group美学,以便线条正确呈现。

library(ggplot2)
library(dplyr)

temp <- 
  data_frame(days = factor(rep(c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"), each = 24),
                           levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")), 
             hour = factor(rep(0:23, 7), levels = 0:23),
             "mean(count)" = rnorm(7*24) 
             )

ggplot(temp) +
  aes(x = hour, y = `mean(count)`, group = days, color = days) +
  geom_point() +
  geom_line() 

enter image description here