ggcats icon indicating copy to clipboard operation
ggcats copied to clipboard

How to add cats in legend?

Open nroak opened this issue 4 years ago • 1 comments

I'm running a simple point plotting with this package. I would like to add this to the legend but since I'm not using any aesthetic, legend doesn't show up. p = p + geom_cat(aes(y=freq,x=category,cat = cats))

nroak avatar Jul 08 '21 22:07 nroak

Hi, at this moment the legend doesn't work as it should. Considering the following example:

set.seed(1)
# Data simulation
x <- runif(30)
y <- 5 * x ^ 2 + rnorm(length(x), sd = 2)
group <- ifelse(x < 0.4, "bongo",
                ifelse(x > 0.8, "nyancat", "toast"))
x <- x + runif(length(x), -0.2, 0.2)

# Data frame
df <- data.frame(x = x, y = y, group = group)


library(ggplot2)
library(ggcats)

# Scatter plot by group
ggplot(df, aes(x = x, y = y, color = group)) +
  geom_cat(cat = group, size = 4)

imagen

This is because the rasterGrob function used within draw_key_cat function only accepts an unique image and at this moment I don't know how to fix it.

draw_key_cat <- function(data, params, size) {

  filename <- system.file(paste0(data$cat, ".png"), package = "ggcats")
  img <- as.raster(png::readPNG(filename))
  aspect <- dim(img)[1]/dim(img)[2]
  # rasterGrob
  grid::rasterGrob(image = img,
                   width = ggplot2::unit(data$size / size, 'snpc'),
                   height = ggplot2::unit(data$size / size * aspect, 'snpc'))
}

If you have any solution please make a PR.

Best regards

R-CoderDotCom avatar Jul 12 '21 10:07 R-CoderDotCom