具有1个数字和2个分类变量的图模型

时间:2014-09-02 13:54:16

标签: r graph glm

我似乎找不到合适的代码来绘制这个模型:

model <- glm( Inter ~ Temp + Period + Vis.Level, data=mydata)

'Inter'是一种称为交互的行为,以分钟为单位进行衡量。数据如下:

Inter Vis.Level    Period Temp
0.0       Low   Morning   17
0.0       Low   Morning   17
0.0       Low   Morning   16
3.0       Low Afternoon   17
3.0       Low Afternoon   16
4.5       Low Afternoon   15
0.0      High   Morning   10
0.0      High   Morning   18
0.0      High   Morning   15
0.0      High Afternoon   17
1.5      High Afternoon   17
0.0      High Afternoon   21

我希望图表看起来像这样

enter image description here

不确定这是否可行,但我们将非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

DF <- read.table(text="Inter Vis.Level    Period Temp
0.0       Low   Morning   17
0.0       Low   Morning   17
0.0       Low   Morning   16
3.0       Low Afternoon   17
3.0       Low Afternoon   16
4.5       Low Afternoon   15
0.0      High   Morning   10
0.0      High   Morning   18
0.0      High   Morning   15
0.0      High Afternoon   17
1.5      High Afternoon   17
0.0      High Afternoon   21", header=TRUE)

#fit your model
fit <- lm(Inter ~ Temp + Period + Vis.Level, data=DF)
#create new data for prediction
DFpredict <- expand.grid(Vis.Level = unique(DF$Vis.Level), 
                         Period = unique(DF$Period),
                         Temp = c(min(DF$Temp), max(DF$Temp)))
#predict
DFpredict$Inter <- predict(fit, newdata=DFpredict)

#plot
library(ggplot2)
ggplot(DF, aes(x=Temp, y=Inter, 
               colour=Vis.Level, shape=Period, linetype=Period)) +
  geom_point() +
  geom_line(data=DFpredict)

resulting plot