带有点的ggplot geom_tile叠加图

时间:2014-07-29 01:27:59

标签: r ggplot2

severity <- c("Major","Serious","Minor","Negligible")
probability <- c("Highly Probable","Probable","Possible","Remote","Unlikely","Impossible")
df <- expand.grid(x=severity,y=probability)
df$x <- factor(df$x, levels=rev(unique(df$x)))
df$y <- factor(df$y, levels=rev(unique(df$y)))
df$color <- c(1,1,2,2,1,2,2,2,2,2,2,3,2,2,3,3,2,3,3,3,3,3,3,3)

ggplot(df,aes(x,y,fill=factor(color)))+
geom_tile(color="black")+
scale_fill_manual(guide="none",values=c("red","yellow","green"))+
scale_x_discrete(expand=c(0,0))+scale_y_discrete(expand=c(0,0))+
labs(x="",y="")

生成风险评估记分卡图表。我想通过添加记录使用csv文件来添加点。每条记录有3个字段,项目名称,x和y坐标。 x =严重性,y =概率。

   da <- data.frame(list(name=c("ENVIRONMENTAL","COSTS","SUPPLY","HEALTH"),
                    severity=c("Major","Serious","Minor","Serious"),
                    probability=c("Probable","Possible","Probable","Unlikely")))
da
           name severity probability
1 ENVIRONMENTAL    Major    Probable
2         COSTS  Serious    Possible
3        SUPPLY    Minor    Probable
4        HEALTH  Serious    Unlikely

> p1 <- p + data.frame(da, aes(severity, probability)) + geom_point()
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
  cannot coerce class ""uneval"" to a data.frame
> 

> d <- data.frame(list(name=c("ENVIRONMENTAL","COSTS","SUPPLY","HEALTH"),
    severity=c(2,3,4,1),probability=c(3,5,4,6)))
> d
           name severity probability
1 ENVIRONMENTAL        2           3
2         COSTS        3           5
3        SUPPLY        4           4
4        HEALTH        1           6
> ggplot(d,x=severity, y=probability)+ geom_point()
Error in exists(name, envir = env, mode = mode) : 
  argument "env" is missing, with no default

如何在ggplot / geom_tile图中添加点?

1 个答案:

答案 0 :(得分:1)

您无法将数据框添加到绘图中(不是那样,至少......)。您可以做的是添加一个新图层geom_point(),并指定它来自的data.frame。为了使事情有效,你应该让你仍然想要使用的任何美学的列(这里,xy)在两个data.frames中具有相同的名称。

# It's better practice to modify your data
# then to convert to factor within the plot
df$color <- factor(c(1,1,2,2,1,2,2,2,2,2,2,3,2,2,3,3,2,3,3,3,3,3,3,3))

# get some meaningful names, that match da and d
names(df)[1:2] <- c("severity", "probability")


p <- ggplot(df, aes(x = severity, y = probability)) +
    # moved fill to the geom_tile layer, because it's only used there
    geom_tile(color = "black", aes(fill = color)) + 
    scale_fill_manual(guide = "none", values = c("red", "yellow", "green")) +
    scale_x_discrete(expand = c(0, 0)) +
    scale_y_discrete(expand = c(0, 0)) +
    labs(x = "", y = "")
    # alsonoticehowaddingspacesmakesiteasiertoread

# Using the same column names? Yup! Now it's this easy:
p + geom_point(data = da) +
    geom_point(data = d, color = "dodgerblue4")