0

Using ggpacket() to create a function and I'd like to name a specific variable edtriage that will be in the dataframe that gets named when using the function (different dataframes supplied each time).

I tried both date_breaks() and breaks() with the same issue. When I supplied the same variable name in geom_text, it worked through aes().

geom_gradient <- ggpacket() +
   geom_link2(aes(group = 1), size = 3, show.legend = FALSE) +   # Gradient line
 geom_point (  size = 5 ) + 
# Below naming always worked
  geom_text_repel(aes(label = if_else(edtriage == max(edtriage),  sprintf("%1.1f%%", Percent), "" )) ,   size = 15 ) + 
  scale_x_date(date_labels="%b\n%y",
              breaks = seq(from = min(.$edtriage), to = max(.$edtriage), by = 0.25), # Not working 
              # breaks = seq(from = min(edtriage), to = max(edtriage), by = 0.25), # Not working either
             date_minor_breaks = "1 month" )  +  
  theme_minimal() 
Cassandra
  • 137
  • 1
  • 9
  • It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Dec 02 '22 at 22:36

1 Answers1

0

You can't add a placeholder directly inside a scale function. I'm not convinced you actually need to here, since you can pass a function to breaks, but one way to achieve what you want is to put a small wrapper round your code that takes a data argument:

library(ggpackets)

geom_gradient <- function(data) {
  ggpacket() +
  ggforce::geom_link2(aes(group = 1), linewidth = 3, show.legend = FALSE) +
  geom_point(size = 5) + 
  ggrepel::geom_text_repel(
    aes(label = dplyr::if_else(edtriage == max(edtriage),  
                               sprintf("%1.1f%%", Percent), "")),   
                  size = 15) + 
  scale_x_date(date_labels = "%b\n%y",
               breaks = seq(min(data$edtriage), max(data$edtriage), 31)) +  
  theme_minimal()
}

This allows:

ggplot(df, aes(edtriage, Percent)) +
  geom_gradient(df)

enter image description here


Data used

set.seed(1)

df <- data.frame(edtriage = seq(as.Date("2021-01-01"), by = "month", len = 24),
                 Percent = runif(24, 60, 100))
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87