更改位于包内的geom_text的字体系列

时间:2014-12-08 22:59:01

标签: r fonts ggplot2 package

使用一个名为Likert的R包,它使用ggplot2,我想更改字体系列。在包中它看起来像这样:

    if(plot.percent.high) {
        p <- p + geom_text(data=lsum, y=100, aes(x=Item,
                        label=paste0(round(high), '%')), 
                        size=text.size, hjust=-.2, color=text.color)
    }

想知道如何在不知道大量此类信息的情况下从包外更改geom_text。对于标签,您可以使用主题,但主题似乎不适用于此。

目前

p = plot(lik) + theme(text = element_text(family = "Georgia"))

将所有其他内容更改为格鲁吉亚。

1 个答案:

答案 0 :(得分:2)

重新评论,您可以修改grobs以更改fontfamily来电中的geom_text

代码包含在函数中,因为您希望复制图形。

library(likert)

# example
data(pisaitems)
items28 <- pisaitems[, substr(names(pisaitems), 1, 5) == "ST24Q"]
l28 <- likert(items28)

# helper function - takes likert plot as input
# loops through the geom_text calls editing the font family
grid_fam <- function(p, fam="Georgia") 
                  {
                  g <- ggplotGrob(p)
                  px <- which(g$layout$name=="panel")
                  id <- grep("text", names(g$grobs[[px]]$children))
                  for(i in id)  g$grobs[[px]]$children[[i]]$gp$fontfamily <- fam
                  grid::grid.newpage()
                  grid::grid.draw(g)
                  invisible(g)
                  }

图解

# original
plot(l28, plot.percents=TRUE, plot.percent.low = FALSE, 
                                             plot.percent.high = FALSE)
# with changed font
grid_fam(plot(l28, plot.percents=TRUE, plot.percent.low = FALSE, 
                                             plot.percent.high = FALSE))

最有可能采用更简单的方法。


编辑评论更新:请随时改进

# initial plot
p <- plot(l28, plot.percents=TRUE, plot.percent.low = FALSE, 
                                             plot.percent.high = FALSE)

# Look at structure of returned ggplot - 
# it does not contain all the info used to generate the plot
str(p)

# g is a gtable which contains the grobs that make up the plot
g <- ggplotGrob(p)
g

# Get the list of parent grobs
g$grobs 

# layout details
g$layout

# we are interested in the grobs with layout name 'panel'
g1 <- g$grobs[[which(g$layout$name=="panel")]]

# have a look at the children within this gTree
childNames(g1)

# look at the structure - we are interested in the grobs with 
# name 'GRID.text.###'
# have a look at fontfamily and its position in the list structure
str(g1)

# extract the position of the grobs with names with 'text' in then
id <- grep("text", names(g$grobs[[which(g$layout$name=="panel")]]$children))

# check
childNames(g1)[id]

# look at grobs to be changed 
str(g$grobs[[which(g$layout$name=="panel")]]$children[id])

# loop through the text grobs changing the fonts
for(i in id)  g$grobs[[which(g$layout$name=="panel")]]$children[[i]]$gp$fontfamily <- "Georgia"

# plot grid obkects
grid::grid.newpage()
grid::grid.draw(g)

# the use of invisible returns the updated gtable if it assigned to a variable
out <- grid_fam(plot(l28, plot.percents=TRUE, plot.percent.low = FALSE, 
                     plot.percent.high = FALSE))

out