user8636730
user8636730

Reputation: 45

How do I label a point with ggplot depending on two different conditions being true?

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.

Upvotes: 1

Views: 3063

Answers (1)

DuckPyjamas
DuckPyjamas

Reputation: 1659

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)

Upvotes: 6

Related Questions