0

I want to

  • plot all data on some layers
    (here: geom_point)
  • plot only a subset on some other layers
    (here: geom_text for type "range")

However, I'm getting the text labels for the whole data, while they should only be added for the turquoise points.

I tried subsetting the data, but the output is not the desired. Still, the object sub_data holds only the wanted data.


Any suggestions?


R code:

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)


output: enter image description here

hardmooth
  • 1,202
  • 2
  • 19
  • 36
  • 1
    I tested your code and I get the desired result. The problem is that you are using `<-` inside the `data.frame` command instead of `=`. – Jaap Jul 17 '14 at 08:07

1 Answers1

2

Change the <- to = inside your data.frame command, like this:

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))
)

Then execute your plot code and you should get the desired result.

An alternative to creating a dataframe in a correct way is:

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)

For more background on the difference between the <- and the = assignment operators, see the answers to this question

Community
  • 1
  • 1
Jaap
  • 81,064
  • 34
  • 182
  • 193
  • Thanks. I 'love' those moments, where the bug lies in so few letters. Still I don't really get, why I can't use '<-' in this case. – hardmooth Jul 17 '14 at 08:23
  • @Jaap: Should one only use '=' and not '<-' while creating dataframe? Some further explanation on = vs <- in this case will be much appreciated. – rnso Jul 17 '14 at 08:24
  • Global vs local scope is very important. Thanks. – rnso Jul 17 '14 at 09:14