Conditional formatting of axis text in faceted ggp

2019-05-06 18:35发布

I'm attempting to make a forest plot of effect sizes from several studies, faceted by their type (X or Y). The dataset includes rows representing the summary statistics for studies of type X and studies of type Y, designated by study=="Summary".

study <- as.factor(c("A","B","C","A","B","Summary","Summary"))
mean  <- c(1.29,0.76,2.43,1.68,1.22,1.7,0.76) 
lowerCI <- c(0.84,0.50,1.58,1.1,0.8,1.11,0.50)
upperCI <- c(1.95,1.16,3.67,2.54,1.85,2.56,1.16)
type <- as.factor(c("X","X","X","Y","Y","X","Y"))

df <- data.frame(study, mean, lowerCI, upperCI, type)
df$study <- as.factor(df$study)

I want to bold the axis tick labels for the summary effect sizes. For some reason, using an ifelse statement doesn't work when I subset. In this sample code, only the summary label for type X is bolded, whereas both should be bolded. In my real, more complex code, neither summary label is bolded.

library(ggplot2)
plot <- ggplot(data=df, aes(y=study, x=mean, xmin=lowerCI, xmax=upperCI, shape = type)) +
  geom_point(color = 'black', size=2)+
  geom_errorbarh(height=.1)+
  geom_point(data=subset(df,study=='Summary'), color='black', size=5)+
  facet_grid(type~., scales= 'free', space='free')+
  theme(axis.text.y= element_text(face=ifelse(levels(df$study)=="Summary","bold","plain")))
print(plot)

It appears that the culprit is the scales='free' code, because if I drop just that or change it to scales='free_x', summary is appropriately bolded twice. However, because I want to drop redundant rows for the studies that are in one subset but not the other (in this example, study C), I need this code to be included.

Is there a workaround?

标签: r ggplot2
1条回答
ゆ 、 Hurt°
2楼-- · 2019-05-06 19:33

You can format each instance of a given tick label across all facets using scale_y_discrete by assigning the desired labels value (including the formatting code) to a corresponding breaks value:

ggplot(data=df, aes(y=study, x=mean, xmin=lowerCI, xmax=upperCI, shape = type)) +
  geom_point(color = 'black', size=2)+
  geom_errorbarh(height=.1)+
  geom_point(data=subset(df,study=='Summary'), color='black', size=5)+
  facet_grid(type~., scales= 'free', space='free') +
  scale_y_discrete(breaks=levels(df$study),
                   labels=c(levels(df$study)[1:3], expression(bold("Summary"))))

enter image description here

查看更多
登录 后发表回答