pyll
pyll

Reputation: 1764

Conditional Shape/Color plot

I have a data frame that looks like this

categories <- c('a', 'b', 'c', 'd', 'e')
trends <- c(.20, -.05, 0, .1, 0)

df <- as.data.frame(categories, trends)

I'm trying to create a plot that has green triangles for positive trends, red triangles for negative trends, and black squares for zero trends.

This is my attempt, but the colors and guide are not coming out right.

ggplot(
  df %>%
    mutate(color_index = ifelse(trends > 0, "green", 
                         ifelse(trends < 0, "red", "black")),
           shape_id = ifelse(trends > 0, 24, 
                      ifelse(trends < 0, 25, 22))),

  aes(x = categories, y = trends, fill = color_index)) +

  # up/down arrow points
  geom_point(aes(shape = shape_id), size = 7) +
  scale_shape_identity() +
  geom_text(aes(label=trends*100), size = 4, nudge_y=-0.01, check_overlap = TRUE) 

enter image description here

Upvotes: 0

Views: 146

Answers (1)

markus
markus

Reputation: 26343

Add scale_fill_identity to your plot

ggplot(df1, aes(x = categories, y = trends, fill = color_index)) +
  # up/down arrow points
  geom_point(aes(shape = shape_id), size = 7) +
  scale_shape_identity() +
  scale_fill_identity() +
  geom_text(aes(label=trends*100), size = 4, nudge_y=-0.01, check_overlap = TRUE) 

enter image description here

data

categories <- c('a', 'b', 'c', 'd', 'e')
trends <- c(.20, -.05, 0, .1, 0)

df <- data.frame(categories, trends)
df1 <- df %>%
  mutate(color_index = ifelse(trends > 0, "green", 
                              ifelse(trends < 0, "red", "black")),
         shape_id = ifelse(trends > 0, 24, 
                           ifelse(trends < 0, 25, 22)))

Upvotes: 3

Related Questions