特定绘图层的数据子集

时间:2014-07-17 07:45:03

标签: r ggplot2

我想

  • 绘制某些图层上的所有数据
    (此处: geom_point
  • 仅在其他一些图层上绘制一个子集(此处: geom_text ,类型为"范围")

但是,我获取了整个数据的文本标签,而它们只应添加为绿松石点。

我尝试对数据进行子集化,但输出并不是理想的。仍然,对象 sub_data 仅包含所需数据。


有什么建议吗?


R代码:

library(ggplot2)

N <- 10

# create 20 = 2*10 data points
test_data <- data.frame(
  idx  <- c( 1:N, 1:N ),
  vals <- c( runif(N, 0, 1),
             rep(  0.5, N)),
  type <- c( rep("range",  N),
             rep("const",  N))
)

# this subsets to the 10 data points of type "range"
sub_data <- subset( test_data, type == "range")

ggplot( test_data, aes( x = idx, y = vals)) + 
  geom_point( aes( colour = type)) +
  geom_text(  data = sub_data, aes( x = idx + 0.1, label = idx ), size = 3.5)


输出: enter image description here

1 个答案:

答案 0 :(得分:2)

<-命令中的=更改为data.frame,如下所示:

test_data <- data.frame(
  idx  = c(1:N, 1:N),
  vals = c(runif(N, 0, 1), rep(  0.5, N)),
  type = c(rep("range", N), rep("const",  N))
)

然后执行您的绘图代码,您应该得到所需的结果。

以正确方式创建数据框的另一种方法是:

idx <- c(1:N, 1:N),
vals <- c(runif(N, 0, 1), rep(  0.5, N)),
type <- c(rep("range", N), rep("const",  N))
test_data <- data.frame(idx, vals, type)

有关<-=作业运算符之间差异的更多背​​景信息,请参阅the answers to this question

相关问题