繁体   English   中英

在R中的线图中删除某个值的点

[英]Deleting points of a certain value in a line plot in R

我目前正在使用R创建折线图。 我正在使用的数据框类似于:

       1989  1990  1991  1992  1993
    A  -30   -16     0     0     0
    B   12    32     7     0     0
    C    0     0     0     0     0
    D    0     3    -8    -6     6
    E    0     0     0     0    -7

每个字母都是单独的一行,年份在x轴上,然后值是y轴。 我希望仅当值不等于零时才显示一行。 我可以轻松地用零绘制点,但是我尝试将0更改为NA,但并没有达到我的预期。

如何绘制图中不存在的0数据?

这是使用ggplot2的一种方法。 但是首先,您必须重塑数据。 我将使用reshape2软件包进行如下操作:

require(reshape2)
# melt the data.frame.. and I've manually added the row names as separate col
dd <- transform(melt(df), grp = LETTERS[1:5])
# change type and replace 0 with NA
dd$variable <- as.numeric(as.character(dd$variable))
dd$value[dd$value == 0] <- NA

require(ggplot2)
ggplot(data = dd, aes(x=variable, y=value, group=grp, colour=grp)) + 
       geom_line() + geom_point()

在此处输入图片说明

这感觉有点骇人听闻,但适用于您的示例数据:

plot(NA, xlim=c(.5,5.5), ylim=c(min(df)-1,max(df)+1),
         xaxt="n", xlab="Year", ylab="Value")
axis(1,1:5,labels=gsub("X","",names(df)))
apply(df,1,function(x) if(sum(!x==0)>0) points((1:ncol(df))[!x==0],x[!x==0],type="b") )

在此处输入图片说明

使用matplot另一种变体,假设在本文末尾使用df 我将其中的一年从1993年更改为1997 1993只是为了证明x轴值被解释为数字,而不是等距的因子。

df[df==0] <- NA
matplot(as.numeric(names(df)),t(as.matrix(df)), type="o",pch=19,lty=1,ann=FALSE)
title(xlab="Years",ylab="Values")

给予:

在此处输入图片说明

以及使用的数据:

df <- read.table(textConnection("
       1989  1990  1991  1992  1997
    A  -30   -16     0     0     0
    B   12    32     7     0     0
    C    0     0     0     0     0
    D    0     3    -8    -6     6
    E    0     0     0     0    -7
"),header=T,check.names=FALSE)

除了@Arun的答案,我建议如果您想删除所有条目均为0的行,则可以使用类似

df[sapply(1:nrow(df), function(i) !all(df[i,] == 0)),]

df是您的data.frame。 这将消除所有元素均为0的所有行,您可以根据需要绘制其余的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM