Home > front end >  How to fix the geom_col(width = 1) in R
How to fix the geom_col(width = 1) in R

Time:12-04

I struggled to fit the geom_col(width = 1) in ggplot2.

Here are my codes:

df <- data.frame(Y = c(0.45, 0.25,  0.05, -0.05, -0.25, -0.45),
                 X = rep(9, n = 6))
df
library(dplyr)
library(ggplot2)
df %>%
  mutate(color = case_when(Y %in% c(-0.45, 0.45, -0.25, 0.25) ~ '#6BD7AF',
                           TRUE ~ 'grey')) %>%
  ggplot(aes(x = X, y = factor(Y), fill = color))  
  geom_col(width = 1)  
  scale_fill_manual('', values = c('#6BD7AF' = '#6BD7AF', 'grey' = 'grey'),
                    labels = c('Incorrect', 'Correct'))  
  theme_classic()  
  labs(y = 'y', x = ' x')  
  coord_cartesian(expand = FALSE, xlim = c(1, NA))  
  scale_x_continuous(breaks = seq(1, 9, by = 1)) 
  scale_y_discrete(labels = seq(-0.5, 0.5, by = 0.2))

I want to fit the grey area in my diagram exactly between -0.1 and 0.1. The codes work perfectly, but not sure why the grey does not fit between -0.1 and 0.1. I also want to use density and angle for the green colour.

CodePudding user response:

You are using a discrete scale, and the centre of bars will always be at the tick marks, so this probably isn't the way to go. A geom_rect would make more sense here. For density and angle fills, you will need ggpattern

library(ggplot2)
library(ggpattern)

df <- data.frame(xmin = rep(0, 3), xmax = rep(9, 3), 
                 ymin = c(-Inf, -0.1, 0.1), ymax = c(-0.1, 0.1, Inf),
                 fill = c("Incorrect", "Correct", "Incorrect"))

ggplot(df)  
  geom_rect_pattern(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, 
                pattern = fill, pattern_fill = fill, fill = fill),
                pattern_colour = NA, pattern_angle = 45,
                pattern_density = 0.3, pattern_spacing = 0.02)  
  theme_classic()  
  labs(y = 'y', x = ' x')  
  coord_cartesian(expand = FALSE, xlim = c(1, NA))  
  scale_x_continuous(breaks = seq(1, 9, by = 1), limits = c(0, 9))  
  scale_y_continuous(limits = c(-0.5, 0.5), breaks = seq(-0.5, 0.5, 0.2))  
  scale_pattern_fill_manual(NULL, values = c("gray", '#6BD7AF'))  
  scale_fill_manual(NULL, values = c("gray", "white"))  
  scale_pattern_manual(NULL, values = c("none", "stripe"))

enter image description here

Created on 2022-12-03 with reprex v2.0.2

  • Related