0

I want to produce a simple heat map where I can manually add striping patterns. I have looked at solutions here and here, and the geom_bin2d_pattern() example here is close, but I cannot get my code to work. Here is what I tried:

library(ggpattern)
library(ggplot2)
library(tidyverse)

df <- data.frame(X = c(1, 1, 2, 2, 3, 3),
                 Y = c(1, 2, 1, 2, 1, 2),
                 Z = c(1, 2, 1, 3, 2, 4),
                 hatches = c("zero", "one", "zero", "one", "zero", "zero"))

ggplot(df, aes(X, Y, pattern = hatches, fill = Z)) +
  geom_tile_pattern(pattern_color = NA,
                    pattern_fill = "black",
                    pattern_angle = 45,
                    pattern_density = 0.5,
                    pattern_spacing = 0.025,
                    pattern_key_scale_factor = 1) +
  scale_pattern_manual(values = c(zero = "stripe", one = "none")) +
  scale_fill_gradient2(low = "blue", mid = "gray", high = "red") +
  geom_tile()

The scale_pattern_manual() line causes this error:

Error: Continuous value supplied to discrete scale

Another problem is that if I comment that line out, there is no blue--just shades of red.

How do I get a transition from blue to gray to red, and how do I get hatches at the upper-left and upper center squares of this heat map?

Forklift17
  • 2,245
  • 3
  • 20
  • 32

1 Answers1

1

The following is a full reprex that seems to be what you want. I don't get the error with the pattern scale running the data and code in your example. Your geom_tile line at the end draws over everything else and should be removed. scale_fill_gradientn is a simple way to get the colors you want on the fill scale.

library(tidyverse)
library(ggpattern)

df <- data.frame(X = c(1, 1, 2, 2, 3, 3),
                 Y = c(1, 2, 1, 2, 1, 2),
                 Z = c(1, 2, 1, 3, 2, 4),
                 hatches = c("zero", "one", "zero", "one", "zero", "zero"))

ggplot(df, aes(X, Y, pattern = hatches, fill = Z)) +
  geom_tile_pattern(pattern_color = NA,
                    pattern_fill = "black",
                    pattern_angle = 45,
                    pattern_density = 0.5,
                    pattern_spacing = 0.025,
                    pattern_key_scale_factor = 1) +
  scale_pattern_manual(values = c(zero = "stripe", one = "none")) +
  scale_fill_gradientn(colors = c("blue", "gray", "red"))

enter image description here

Created on 2022-09-28 with reprex v2.0.2

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87