On occasion, I have the need for some kind of pattern or textures for geom_bar() / geom_col() bars (i.e., for black-and-white printing). For example, the following can be hard for some people to view:
library(ggplot2)
library(dplyr, warn.conflicts=FALSE)
library(tidyr)
d <- iris %>%
group_by(Species) %>%
summarize_all(mean) %>%
gather(key, val, -Species)
ggplot(d, aes(x = Species, y = val, fill = key)) +
geom_col(position = "dodge") +
scale_fill_grey()
There have been good questions and answers on Stack Overflow (also here). However, the solutions are complicated and basically involve creating the patterns or textures by hand. I'm wondering if anyone has general ideas or suggestions or new approaches to solving this problem in a different way. Oftentimes when I think I can't do something with ggplot2, it means changing how I think about addressing it - but other (rare) times it just isn't implemented yet!
There are two types of bar charts: geom_bar() and geom_col() . geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.
In the above example, we've overridden the default count value by specifying stat = "identity" . This indicates that R should use the y-value given in the ggplot() function. Notice that bar graphs use the fill argument instead of the color argument to color-code each cut category.
Basically, geom_col is a wrapper over the geom_bar geometry, which has statically defined the statistical transformation to identity. This means that the values for positional parameters x and y are mapped directly to variables from the selected dataset.
You can add patterns using the ggpattern
package
# remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
library(ggplot2)
library(dplyr, warn.conflicts=FALSE)
library(tidyr)
d <- iris %>%
group_by(Species) %>%
summarize_all(mean) %>%
gather(key, val, -Species)
ggplot(d, aes(x = Species, y = val, fill = key)) +
geom_col_pattern(position = "dodge",
pattern =
c(
"stripe", "stripe", "stripe", # 3rd col
"stripe", "stripe", "stripe", # 4th col
"none", "none", "none", # 1st col
"crosshatch", "crosshatch", "crosshatch" # 2nd col
),
pattern_angle = c(rep(0, 3),
rep(45, 3),
rep(0, 6)),
pattern_density = .1,
pattern_spacing = .04,
pattern_fill = 'black') +
scale_fill_grey() +
guides(fill = guide_legend(override.aes =
list(
pattern = c("none", "crosshatch", "stripe", "stripe"),
pattern_spacing = .01,
pattern_angle = c(0, 0, 0, 45)
)
))
Created on 2021-01-13 by the reprex package (v0.3.0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With