ggplot2: Formatting Legend Categories

若如初见. 提交于 2020-01-11 03:57:49

问题


I would like to be able to do something like this: https://stackoverflow.com/a/30036603, except with "legend.text" instead of "axis.text.x". Is this possible?

It would be something like this, except it's not currently working (all labs are italicized):

data <- data.frame(labs = c("Oranges", "Apples", "Cucumbers"), counts = c(5, 10, 12))

ggplot(data = data) +
geom_bar(aes(x = labs, y = counts,fill=labs), stat="identity") +
theme(axis.text.x=element_text(face=ifelse(levels(data$labs)=="Cucumbers","plain","italic"))) +
  theme(legend.text=element_text(face=ifelse(levels(data$labs)=="Cucumbers","plain","italic")))

回答1:


Rather than messing with the theme, you can adjust the scales to draw expressions which can include italic words. For example

toexpr<-function(x) {
  getfun <- function(x) {
    ifelse(x=="Cucumbers", "plain", "italic")
  }
  as.expression(unname(Map(function(f,v) substitute(f(v), list(f=as.name(f), v=as.character(v))), getfun(x), x)))
}

ggplot(data = data) +
  geom_bar(aes(x = labs, y = counts,fill=labs), stat="identity") +
  scale_x_discrete(breaks =levels(data$labs), labels = toexpr(levels(data$labs))) +
  scale_fill_discrete(breaks=levels(data$labs), labels = toexpr(levels(data$labs))) + 
  theme(legend.text.align = 0)



来源:https://stackoverflow.com/questions/44641870/ggplot2-formatting-legend-categories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!