monkeyshines
monkeyshines

Reputation: 1078

Use ggplot to plot over an image with legend

I would like to map OHS incidents over a PNG of a hospital floorplan using ggplot2. I have tried reading this non-geographic map in as a ggimage.

ICU Floor Plan

So far I have tried the following with the dataset (14462) observations that I have.

Example dataset

toy <- data.frame(patient_ID = c(1001,1001,1002,1003,1004), 
               SEX = c("M","M","F","F","F"),
              phenotype = c("Psychiatric","Psychiatric", "Cardio",
                            "Cancer","Psychiatric"),
                            x = c(0.5737, 0.5737, 0.6968, 0.4704, 0.6838),
                            y= c(0.3484, 0.3484, 0.62, 0.5216, 0.2486))

I have tried reading the file in as a raster and then using ggmaps but the difficulty is no legend.

library(ggmap)
library(png)
library(ggplot2)
library(data.table)

toy <- fread("toy.csv")

# read in image 

r <- readPNG("ICU-crop.png")

#use ggimage to convert to plot and add gender
ggimage(r, scale_axes = TRUE) +
  geom_point(aes(x = x, y = y, colour = SEX), data = toy,
             size = I(1), fill = NA)

I would really like to use ggplot but need the legend. I am not sure what other methods I can use to ggplot over a PNG.

Upvotes: 5

Views: 670

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78832

The real "magic" for this is just fullpage=FALSE in the call to ggimage(), but you'll have to clean up axes a bit then:

ggimage(r, fullpage = FALSE, scale_axes = TRUE) +
 geom_point(aes(x = x, y = y, colour = SEX), 
            data = toy, size = I(1), fill = NA) +
  labs(x=NULL, y=NULL) +
  theme(axis.text=element_blank()) +
  theme(axis.ticks=element_blank())

enter image description here

You should prbly clean up the legend, too and I'd suggest lightening the base image a bit since it will be difficult to see the contrast between it and the colors you're going to overlay (unless they're large objects).

Upvotes: 5

Related Questions