metalaureate
metalaureate

Reputation: 7732

ggplot: Conditionally format point based on a variable that isn't shown

I want to show the point as hollow if the p score is greater than 0.1 in the following chart, but I can't figure out how to make the formatting of that point conditional on the value of p:

enter image description here

Data frame can be reproduced using this code:

structure(list(metric = structure(1:6, .Label = c("Viewers", 
"Views", "Chatters", "Chats", "Diamond Senders", "Diamonds"), class = "factor"), 
    group = c("Views", "Views", "Chats", "Chats", "Diamonds", 
    "Diamonds"), avg = c(-0.0264387458383021, -0.0515928340053015, 
    0.0097420053047867, 0.144967615821856, 0.347281593023006, 
    -0.25567948486292), err_low = c(-0.0664593483464582, -0.139178443719337, 
    -0.0595290104397667, -0.0490217193008488, -0.146892412146765, 
    -1.24468943017821), err_high = c(0.013581856669854, 0.0359927757087344, 
    0.0790130210493401, 0.33895695094456, 0.841455598192777, 
    0.733330460452365), p = c(0.277195141257042, 0.332587114951675, 
    0.817060323071668, 0.218997456845286, 0.247710490053607, 
    0.670666890004374), ord = c(1, 2, 3, 4, 5, 6)), .Names = c("metric", 
"group", "avg", "err_low", "err_high", "p", "ord"), row.names = c(NA, 
-6L), class = "data.frame")

Chart can be reproduced with ggplot2 using:

ggplot(datac, aes(x=metric, y=avg, color=group)) +geom_hline(yintercept = 0)+
      geom_label(aes(label=paste0(round(avg*100,2),"%")),nudge_x=-0.35, size=2.5) +geom_point(size=6)+ 
    geom_errorbar(position=position_dodge(.9), width=.25, aes(ymin=err_low, ymax=err_high)) +
     theme_minimal()+  scale_color_manual(values=c("Views"="blue", "Chats"="orange","Diamonds"="dark green")) +
     scale_y_continuous(labels = scales::percent,breaks=c(seq(-2,+2,by=0.2))) + labs(title="Change in Test vs. Control", 
         x="Experiment Metrics ", y = "% change")

Thank you for a solution!

Upvotes: 1

Views: 478

Answers (1)

missuse
missuse

Reputation: 19716

Easiest way is to create another factor column with the desired mapping and apply it on the graph. I used p > 0.5 in the example

library(dplyr)
datac %>%
  mutate(p1= factor(ifelse(p > 0.5, 1, 0)))%>%
  ggplot(aes(x=metric, y=avg, color=group))+
  geom_hline(yintercept = 0)+
  geom_label(aes(label=paste0(round(avg*100,2),"%")),nudge_x=-0.35, size=2.5)+
  geom_point(size=6, aes(shape = p1))+
  geom_errorbar(position=position_dodge(.9), width=.25, aes(ymin=err_low, ymax=err_high))+
  theme_minimal()+
  scale_color_manual(values=c("Views"="blue", "Chats"="orange","Diamonds"="dark green")) +
  scale_y_continuous(labels = scales::percent,breaks=c(seq(-2,+2,by=0.2)))+
  labs(title="Change in Test vs. Control", x="Experiment Metrics ", y = "% change")+
  scale_shape_manual("p > 0.5", values=c("0" = 1, "1" = 16))

enter image description here

Upvotes: 3

Related Questions