Exsixio
Exsixio

Reputation: 3

Changing Y Axis Tick mark labels to hyperlinks

I am using ggplot() to graph the price range of 20 different products. I am looking to change the y axis plot tick mark labels to the product name and embed a link to where the data is pulled from. I am not even sure this is possible.

I have tried this.

ggplot(testdata, aes(x = value, y=variable)) +
  geom_boxplot() geom_link(
  x = testdata$value,
  y = testdata$variable,
  href = testdata$href,
  parse = FALSE)

I have also tried this

urls <-c("www.example.com/1","www.example.com/2",
"www.example.com/3") #(shortened here for brevity)
ggplot(testdata, aes(x = value, y=variable)) +
    geom_boxplot() +
    scale_y_continous(
    labels = paste0("<a href='", urls, "'>", testdata$x, "</a>")
    )  +
theme(axis.text.y = element_markdown)
  parse = FALSE)

Upvotes: 0

Views: 49

Answers (1)

margusl
margusl

Reputation: 17354

Not (just) {ggplot} nor y-axis labels, but we can get quite close with {ggiraph} and a few *_interactive() elements when using facets:

library(ggplot2)
library(ggiraph)

gg <- ggplot(iris, aes(x = Sepal.Length)) +
  geom_boxplot() +
  facet_grid_interactive(rows = vars(Species), switch = "y", 
                         labeller = labeller_interactive(
                           aes(onclick = sprintf('window.open("https://www.google.com/search?q=%s")', Species)))) +
  theme(axis.text.y = element_blank(), 
        axis.ticks.y = element_blank(), 
        panel.grid.major.y = element_blank(),
        panel.grid.minor.y = element_blank(),
        strip.placement = "outside",
        strip.background = element_blank(),
        strip.text.y = element_text_interactive())

girafe(ggobj = gg)

Created on 2023-10-16 with reprex v2.0.2

Clicking on strip labels ( setosa / versicolor / virginica ) triggers onclick events wich will open links to Google searches.

Upvotes: 0

Related Questions