改进的马赛克图(如热图或气泡)

时间:2015-09-23 14:58:51

标签: r ggplot2 crosstab

我有两个因素,我正在制作交叉表。

x<-table(clean$VMail.Plan,clean$International.Plan)

我实际上想以图形方式表示它:

enter image description here

mosaicplot(x,data=clean,color=2:4,legend=TRUE,las = 1)

正常的镶嵌图不是很吸引人,我不能使用ggplot2包使这更具吸引力。要么像热图还是泡泡?

实际的列联表:

        No   Yes
  No    27  239
  Yes  243 2159

1 个答案:

答案 0 :(得分:8)

首先将数据重新整理为长格式:

library(reshape2)
x <- melt(df)
names(x) <- c("iplan","vplan","value")

之后,您可以轻松制作一个情节,例如geom_point

library(ggplot2)
ggplot(x, aes(iplan, vplan)) +
  geom_point(aes(size = value), alpha=0.8, color="darkgreen", show_guide=FALSE) +
  geom_text(aes(label = value), color="white") +
  scale_size(range = c(15,50)) +
  theme_bw()

这给出了:

enter image description here

作为替代方案,您还可以考虑geom_tile

ggplot(x, aes(iplan, vplan)) +
  geom_tile(aes(fill = value)) +
  geom_text(aes(label = value), color="white") +
  scale_x_discrete(expand = c(0,0)) +
  scale_y_discrete(expand = c(0,0)) +
  scale_fill_gradient("Legend label", low = "lightblue", high = "blue") +
  theme_bw()

给出:

enter image description here

使用过的数据:

df <- structure(list(iplan = structure(1:2, .Label = c("No", "Yes"), class = "factor"), No = c(27L, 243L), Yes = c(239L, 2159L)), .Names = c("iplan", "No", "Yes"), class = "data.frame", row.names = c(NA, -2L))