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,140
  • 2
  • 17
  • 31
  • 1
    I tested your code and I get the desired result. The problem is that you are using ` – 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
  • 77,147
  • 31
  • 174
  • 185