r - 在气泡图中包含 NA 的频率

标签 r plot

我有一个数据框,如下所示:

Data<- data.frame(item1=c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, NA, 5, NA, NA), 
                  item2=c(1, 2, 2, 4, 1, 1, 2, 3, 5, 5, NA, NA, NA, NA),
                  item3=c(1, 2, 2, 4, 1, 1, 2, 3, 5, 5, NA, NA, NA, NA),
                  item4=c(1, 2, 2, 4, 1, 1, 4, 3, 1, 5, NA, 3, NA, NA),
                  item5=c(1, 5, 2, 4, 2, 1, 2, 3, 5, 5, NA, NA, 1, NA))

我已经定义了一个函数,可以提取列频率并在没有 NA 的情况下绘制它

frequencies <- function(x,K=5)
{
  p <- length(x) # items
  n <- nrow(x) # observations
  r <- (5, NA) # values
  myf <- function(y) # extract frequencies
  {
    y <- y[!is.na(y)]
    y <- as.factor(y)
    aux <- summary(y)
    res <- rep(0, r)
    res[1:r %in% names(aux)] <- aux
    100 * res / sum(res)
  }

  freqs <- apply(x, 2, FUN = myf) #  apply myf by columns
  df2 <- expand.grid(vals = 1:r, item = 1:p) # all possible combinations
  df2$freq <- as.numeric(freqs) # add frequencies

  # graph
  plot(df2$item,df2$vals,type="n",xlim=c(1,p),ylim=c(1,r),xaxt = "n",
       xlab="", ylab="", ann=FALSE)


  axis(1, labels=FALSE)
  labs <- paste(names(x))   ##labels=c("v1", "v2", ...)
  text(1:p,  srt = 60, adj=0.5, pos=1, las=2,
       labels = labs, xpd = TRUE, par("usr")[1], cex.main=0.8, offset=1)



  points(df2$item,df2$vals,pch=22,col="black", bg="gray", cex=(df2$freq/n)*K)
}

我希望将 NA 绘制为“值”(在 y 坐标中),这样我的图可以看起来与该图类似(已使用编辑器编辑过,没有 R): enter image description here

提前谢谢您,

安古洛

最佳答案

另一种可能性是,您将数据融化为长格式,然后使用exclude = NULLtable进行计数,也可以对NA进行计数。如果您想让频率与方 block 的面积而不是宽度成正比,请选中scale_size_area

library(reshape2)
library(ggplot2)

Data2 <- melt(Data)
Data3 <- with(Data2, as.data.frame(table(variable, value, exclude = NULL)))
Data3 <- Data3[!is.na(Data3$variable), ]

ggplot(data = Data3, aes(x = variable, y = value, size = Freq)) +
  geom_point(shape = 0)

enter image description here

关于r - 在气泡图中包含 NA 的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754194/

相关文章:

r - "Cut out"R中的3D曲面图

svg - 将参数传递给 HandlerFunc

r - 如何在 R 中求解和绘制微分方程

r - 在 dplyr 中使用 group_by 时如何获得总体统计数据?

r - hist.default(xa) : 'x' must be numeric 中的错误

python - matplotlib 图表区域 vs 绘图区域

python - 在没有 %matplotlib 魔法函数的 IPython Notebook 中包含绘图

plot - 带有 PLplot、OCaml 的标题

linux - DMwR linux 缺少软件包

r - Hmisc波浪号行名