R 如何绘制数据框的多列以查看每列中的数据位置?
我随身携带以下数据框:R 如何绘制数据框的多列以查看每列中的数据位置?,r,plot,ggplot2,dataframe,missing-data,R,Plot,Ggplot2,Dataframe,Missing Data,我随身携带以下数据框: Index | ColA | ColB | ColC | ColD 1 | NA | NA | 0 | NA 2 | NA | 0 | 1 | 0 3 | NA | NA | 2 | 1 4 | 1 | 0 | 2 | 2 5 | NA | NA | 2 | NA 6 | NA | 1
Index | ColA | ColB | ColC | ColD
1 | NA | NA | 0 | NA
2 | NA | 0 | 1 | 0
3 | NA | NA | 2 | 1
4 | 1 | 0 | 2 | 2
5 | NA | NA | 2 | NA
6 | NA | 1 | 1 | 1
7 | 0 | 1 | 0 | 2
8 | NA | 2 | 0 | 2
9 | NA | 0 | NA | 1
10 | 2 | 1 | 0 | 0
现在,我想用R来绘制这些数据,其中X轴是索引列,Y轴表示其余的列名(ColA、ColB、ColC和ColD)。图中的每个x-y点应表示是否存在NA或非NA。与此类似(对于上述数据帧):
提前感谢您的帮助 这里有一种使用
绘图的方法
# get values of x axis from data as a vector
xVals <- as.integer(!is.na(df)) * 1:10
# get values of y axis
yVals <- rep(1:4, each=10)
# add appropriate NAs
is.na(xVals) <- xVals == 0
is.na(y) <- is.na(xVals)
# plot the results
plot(xVals, yVals)
#以矢量形式从数据中获取x轴的值
xVAL以下是使用ggplot
绘制的曲线图:
资料
谢谢,杰森,它就像一个符咒,是我一直在寻找的东西。很高兴听到这个消息!谢谢你的回复!虽然我还没有测试,但您的解决方案也可能是正确的,但我正在寻找一个能够处理大型数据集的解决方案。
# get values of x axis from data as a vector
xVals <- as.integer(!is.na(df)) * 1:10
# get values of y axis
yVals <- rep(1:4, each=10)
# add appropriate NAs
is.na(xVals) <- xVals == 0
is.na(y) <- is.na(xVals)
# plot the results
plot(xVals, yVals)
set.seed(1234)
df <- data.frame(ColA=sample(c(0:2,NA), size=10, replace=T, prob=c(.2,.2,.2,.4)),
ColB=sample(c(0:2,NA), size=10, replace=T, prob=c(.2,.2,.2,.4)),
ColC=sample(c(0:2,NA), size=10, replace=T, prob=c(.2,.2,.2,.4)),
ColD=sample(c(0:2,NA), size=10, replace=T, prob=c(.2,.2,.2,.4)))
df <- structure(list(Index = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
ColA = c(NA, NA, NA, 1, NA, NA, 0, NA, NA, 2),
ColB = c(NA, 0, NA, 0, NA, 1, 1, 2, 0, 1),
ColC = c(0, 1, 2, 2, 2, 1, 0, 0, NA, 0),
ColD = c(NA, 0, 1, 2, NA, 1, 2, 2, 1, 0)),
.Names = c("Index", "ColA", "ColB", "ColC", "ColD"),
row.names = c(NA, -10L), class = "data.frame") 0, 1, 2, NA, 1, 2, 2, 1, 0)), .Names = c("Index", "ColA", "ColB", "ColC", "ColD"), row.names = c(NA, -10L), class = "data.frame")
library(ggplot2)
library(reshape2)
ggplot(melt(df, "Index"), aes(x=as.factor(Index), y=variable, alpha=!is.na(value))) +
geom_point() +
labs(x="Index", y="Variable") +
scale_alpha_discrete("", breaks=c(TRUE, FALSE), labels=c("Not NA", "NA"))