label only subset of points in a ggplot where x wa

2019-08-25 04:04发布

问题:

I have this kind of table:

dt <- data.table(titles=c('B','C','A','C'),
                 labs  =c('b','c','a','c'),
                 values=c( 3, 2, 3, 4))

In order to plot the points without collapsing and re-ordering, I had to do the following trick with ggplot(): instead of aes(x=titles, y=values) I use aes(x=seq_len(nrow(dt)), y=values):

ggplot(data = dt, 
       aes(x=seq_len(nrow(dt)), y=values)) + 
  geom_point() +
  geom_text(aes(label=labs)) +
  scale_x_discrete(labels=dt$titles) + xlab('titles')

Now I want to have labels not for all points but only for a subset of them (for example, where values>2). This call doesn't work:

ggplot(data = dt, 
       aes(x=seq_len(nrow(dt)), y=values)) + 
  geom_point() +
  geom_text(data=subset(dt, values>2), aes(label=labs)) +
  scale_x_discrete(labels=dt$titles) + xlab('titles')
 # Error: Aesthetics must be either length 1 or the same as the data (2): label, x, y

How to call geom_text() in this case?

回答1:

I think you are looking for the inherit.aes=F option:

dt2 <- subset(dt, values>2)
ggplot(data = dt, 
       aes(x=seq_len(nrow(dt)), y=values)) + 
  geom_point() +
  geom_text(data=dt2, aes(x=values, y=values, label=labs), inherit.aes=F) +
  scale_x_discrete(labels=dt$titles) + xlab('titles')


标签: r ggplot2