更改标签的字体大小而不知道ggplot2

时间:2016-06-21 12:26:04

标签: r ggplot2 r-grid

我想更改此图中标签的字体大小:

library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + 
        geom_text(label=rownames(mtcars))
p

mtcars plot

我的问题:我不知道标签是什么。(我存储了一个情节,其中我使用了不同的data.frame()add geom_text()。我现在只加载了plot(此示例中为p),但不想加载我创建标签的data.frame()

由于我不知道标签是什么,我不能使用这个解决方案:

p + geom_text(label=rownames(mtcars), size=2)

(此解决方案的另一个问题是我仍然需要删除具有较大字体大小的原始geom_text())。

我可以使用此解决方案更改绘图中所有文本的大小:

library(grid)    
grid.force()
grid.gedit("GRID.text", grep=TRUE, gp=gpar(fontsize=4.5))

然而,现在我的轴也发生了变化,这不是我想要的。

我相信有几种选择可以达到我想要的目标,其中至少有两种选择应该相当简单:

  1. 将对象从grid.gedit()保存到p1,然后再保存到p1 + theme(text = element_text(size=2))。我的问题在这里:我不知道如何从grid.gedit()保存对象。 这是我的首选选项。

  2. 在应用grid.gedit()之前,请转到右侧视口。我试过这个,但仍然改变了标签(我想要的)和轴文本(我不想要)。

  3. 以某种方式从存储的图(本例中为data.frame)中提取标签的p,以应用我首先提供的解决方案。

2 个答案:

答案 0 :(得分:3)

您可以在构建之后检查(/修改)图,

library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + 
  geom_text(label=rownames(mtcars))

g <- ggplot_build(p)
# original data is in str(g$plot$data)

# but it's easier to process the data for rendering
g[["data"]][[1]][["size"]] <- 5
g[["data"]][[1]][["colour"]] <- "red"

gg <- ggplot_gtable(g)
grid.newpage()
grid.draw(gg)

enter image description here

答案 1 :(得分:1)

您的grid.gedit命令已关闭。您需要设置gPath,以便编辑命令仅在绘图面板中找到这些标签。 grid.ls(grid.force())返回grobs的层次结构。找到“面板”,然后找到“文本”。 (注意:'gedit'中的'g'代表'grep = TRUE,global = TRUE')

library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + 
        geom_text(label=rownames(mtcars))
p

library(grid)    
grid.ls(grid.force())   # Locate the path to the labels in the panel
grid.gedit(gPath("panel","GRID.text"), gp=gpar(fontsize=4.5))

如果您愿意,可以使用更多代码行来编辑绘图对象,而不是在屏幕上进行编辑。

g = ggplotGrob(p)
g = editGrob(grid.force(g), gPath("panel", "GRID.text"), grep=TRUE, gp=gpar(fontsize=4.5))
grid.newpage()
grid.draw(g)

enter image description here