0

Hi I been getting Aesthetics error when trying to only display labels for certain subsets. For example.

library("ggplot2")
library(gplots)
library(ggrepel)

set.seed(10)
data <- data.frame(label=letters[1:21], number= runif(21, min=0, max=100))
data$label <-factor(data$label)

ggplot(data, aes(x=label, y=number, fill=data$label )) +
geom_bar(stat="identity") +
geom_text_repel(data=  data[data$number > 80,], aes(label =data$label ), 
                  arrow = arrow(length = unit(0.01, 'npc')), box.padding = unit(1.5, 'lines'),color="black"   )

When I do this I get the following error

Error: Aesthetics must be either length 1 or the same as the data (2): label, x, y, fill

even if I replace the label with a vector such as c("label1","label2") I still get an error.

I'm doing something wrong but I can't figure it out. The only way I can do this is to create a separate vector with the same length and use that as the label, however I think there is a way to subset directly. thanks!

Ahdee
  • 4,679
  • 4
  • 34
  • 58

1 Answers1

3

Change the code to:

ggplot(data, aes(x=label, y=number, fill=data$label )) +
geom_bar(stat="identity") +
geom_text_repel(data=  data[data$number > 80,], aes(label =label ), ##<- Change here
                  arrow = arrow(length = unit(0.01, 'npc')), box.padding = unit(1.5, 'lines'),color="black"   )

The problem is that in the call to aes within geom_text_repel() you use data$label, a column within the 21 row dataframe, whereas you want label to be evaluated within the 2 row subset of the data.

In this case, you've obscured the problem by calling your data data, it might be more straightforward to spot the error if you'd called it something more meaningful.

Miff
  • 7,486
  • 20
  • 20
  • great thanks, it still failed, but your comment help since I notice that the fill was also incorrect with data$label. It worked as soon as changed it to label. `ggplot(data, aes(x=label, y=number, fill=label )) + geom_bar(stat="identity") + geom_text_repel(data= data[data$number > 80,], aes(label =label ), ##<- Change here arrow = arrow(length = unit(0.01, 'npc')), box.padding = unit(1.5, 'lines'),color="black" )` thanks again; much appreciate it, A – Ahdee Mar 20 '17 at 17:41