Home > front end >  How I can makea plot which I have customized in R
How I can makea plot which I have customized in R

Time:12-04

I want to plot the following plotenter image description here

The x-axis ranges from 1 to 9, and the y-axis ranges from -0.5 to 0.5. I have also specified colours within the boxes

CodePudding user response:

First I created some reproducible data with Y factors and X values. You could define the correct and incorrect colors in a new column using case_when. To create bars use geom_col and scale_fill_manual to define the labels for your colors. Here is a reproducible example:

# Data
df <- data.frame(Y = rep(c(0.3, -0.1, -0.3), each = 9),
                 X = rep(c(1:9), n = 3))

library(dplyr)
library(ggplot2)
df %>%
  mutate(color = case_when(Y == 0.3 | Y == -0.3 ~ 'orange',
                           TRUE ~ 'grey')) %>%
  ggplot(aes(x = X, y = factor(Y), fill = color))  
  geom_col(width = 1)  
  scale_fill_manual('', values = c('orange' = 'orange', 'grey' = 'grey'),
                    labels = c('Correct', 'Incorrect'))  
  theme_classic()  
  labs(y = 'Y', x = '')

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


Update

Slightly modify the data:

df <- data.frame(Y = rep(c(0.45, 0.25, 0.05, -0.05, -0.25, -0.45), each = 9),
                 X = rep(c(1:9), n = 6))

library(dplyr)
library(ggplot2)
df %>%
  mutate(color = case_when(Y %in% c(-0.45, 0.45, -0.25, 0.25) ~ 'orange',
                           TRUE ~ 'grey')) %>%
  ggplot(aes(x = X, y = factor(Y), fill = color))  
  geom_col(width = 1)  
  scale_fill_manual('', values = c('orange' = 'orange', 'grey' = 'grey'),
                    labels = c('Correct', 'Incorrect'))  
  theme_classic()  
  labs(y = 'Y', x = '')

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


Update to axis

You can use the following code:

df <- data.frame(Y = c(0.45, 0.25, 0.05, -0.05, -0.25, -0.45),
                 X = rep(9, n = 6))

library(dplyr)
library(ggplot2)
df %>%
  mutate(color = case_when(Y %in% c(-0.45, 0.45, -0.25, 0.25) ~ 'orange',
                           TRUE ~ 'grey')) %>%
  ggplot(aes(x = X, y = factor(Y), fill = color))  
  geom_col(width = 1)  
  scale_fill_manual('', values = c('orange' = 'orange', 'grey' = 'grey'),
                    labels = c('Correct', 'Incorrect'))  
  theme_classic()  
  labs(y = 'Y', x = '')  
  coord_cartesian(expand = FALSE, xlim = c(1, NA))  
  scale_x_continuous(breaks = seq(1, 9, by = 1))

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

  • Related