1

Lets say that I have a dataframe with two variables. We will call those variables x and var_count. We shall say that var_count is only integers and is categorical in nature (i.e. all values will be 1, 2, 3, 4, or 5). I want to plot the x variable on the y-axis and the var_count variable on the x-axis. I then want to label with geom_text the highest x value for a given var_count. So for all elements with a var_count of 1, I want to only label that element that has the highest x.

I have the code for most of written but not the condition to detect this situation and say "yes, this point needs to be labeled". How do I write this last condition?

So here is some sample code with some sample data.

library(tidyverse)
library(ggplot)
sample_data <- tibble(var_count = c(1, 1, 1, 1, 2, 2, 2, 5),
                      x = c(0.2, 1.1, 0.7, 0.5, 2.4, 0.8, 0.9, 1.3))

sample_data %>%
  ggplot(aes(x = var_count, y = x)) +
  geom_point() +
  geom_text(aes(label =ifelse(
    FALSE,
    "my label", ""
  )), hjust = 1.2)

I want to replace the ifelse's condition from FALSE to work so that the points circled in the following image are labeled:

Pretty much, I want to label the highest x value for a given var_count.

  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. It would probably be easier to subset the data for that layer rather than conditionally put in a aesthetic – MrFlick Nov 21 '19 at 21:51
  • A sample of the data is coming right up. – user8636730 Nov 21 '19 at 21:52
  • 2
    Alright, I made the edits! Does this help? – user8636730 Nov 21 '19 at 22:01

1 Answers1

6

It's easiest to do this inside the dataframe itself. Make a new column where you do the ifelse() or case_when(), giving the column a blank string "" if the condition is FALSE. Then use that as the label text.

library(tidyverse)
library(ggrepel)

my_iris <- 
    iris %>% 
    group_by(Species) %>% 
    mutate(my_label = ifelse(Sepal.Width == max(Sepal.Width),
                             paste(Sepal.Width, "cm"), "")) %>% 
    ungroup()

ggplot(my_iris, aes(x = Petal.Length, y = Sepal.Width, colour = Species)) +
    geom_point() +
    geom_text_repel(aes(label = my_label), box.padding = 2)

Created on 2019-11-22 by the reprex package (v0.2.1)

DuckPyjamas
  • 1,539
  • 13
  • 17