Using italic() with a variable in ggplot2 title expression

狂风中的少年 提交于 2019-12-17 20:47:47

问题


When I make a map using ggplot2 and attempt to italicize part of the figure title using a combination of expression() and italic() using a string, my map comes out as desired:

plottitle <- expression(paste('Example map with ', italic('italics')))

crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
states_map <- map_data("state")
map <- ggplot(crimes, aes(map_id = state)) + 
  geom_map(aes(fill = Murder), 
           map = states_map) + 
  expand_limits(x = states_map$long, 
                y = states_map$lat) +
  labs(title = plottitle)

map

However, when I try to do the same thing, but use an object instead of a string, the object does not evaluate to the desired string:

word <- 'italics'
plottitle2 <- expression(paste('Example map with ', italic(word)))

map <- ggplot(crimes, aes(map_id = state)) + 
  geom_map(aes(fill = Murder), 
           map = states_map) + 
  expand_limits(x = states_map$long, 
                y = states_map$lat) +
  labs(title = plottitle2)

map

How can I get the vector word to evaluate before applying italic()?


回答1:


bquote or substitute should work,

 a = 'text' 
 plot(1,1, main=bquote(italic(.(a))))
 plot(1,1, main=substitute(italic(x), list(x=a)))


来源:https://stackoverflow.com/questions/31927984/using-italic-with-a-variable-in-ggplot2-title-expression

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