ggplot中geom_text字体大小的控制

143

我尝试通过类似以下方式将ggplot2柱状图标签的字体大小更改为10:

ggplot(data=file,aes(x=V1,y=V3,fill=V2)) +
    geom_bar(stat="identity",position="dodge",colour="white") + 
    geom_text(aes(label=V2),position=position_dodge(width=0.9),
                                                 hjust=1.5,colour="white") +
    theme_bw()+theme(element_text(size=10))

ggsave(filename="barplot.pdf",width=4,height=4)

但生成的图表标签字体超大。

然后我考虑在 geom_text() 中进行修改:

geom_text(size=10,aes(label=V2),position=position_dodge(width=0.9),
                                                   hjust=1.5,colour="white")

标签字体甚至更大...

我可以在 geom_text 中更改大小,比如改为3,现在它看起来像字体10,类似于轴标签。

我想知道是怎么回事? theme(text=element_text(size=10)) 不适用于标签吗?

为什么 geom_text() 中的大小为10与 theme(text=element_text()) 中的大小不同?

4个回答

218

以下是更改文本/标签大小的几个选项

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

geom_text中的size参数可以调整标签(labels)的大小。

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)

为什么 geom_text() 中的 size 值与 theme(text=element_text()) 中的值不同?

是的,它们是不同的。我进行了快速手动检查,它们的比例约为(14/5)的 geom_text 大小与 theme 大小。因此,一种可怕的解决方案是按比例缩放以获得统一的大小。

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

当然,这并没有解释为什么?而且这很麻烦(我认为有一种更合理的方法来解决这个问题)


2
有趣,你检查了什么以发现14/5的比率? - olala
49
我明白了。你让我想起了最近读过的一些东西,我猜这是单位上的差别。geom_text默认为5,可能指的是5毫米,而theme()中的大小单位是点。1个点等于1/72英寸=0.35毫米,因此在geom_text()中1代表1毫米,1/0.35约等于14/5 :) - olala
6
agstudy的回答解释了为什么ggplot2中的size单位是mm。 - user20650
3
对于想要将 geom_text 转换为“正常”字体大小的人,只需 乘以 0.36 即可。 - Nova

6
我有一个问题,并在 ggplot帮助页面的美学规范上找到了答案。他们提供了一个方便的函数,用于将毫米(默认为geom_text以保持与线条和点的一致性)转换为点(主题的比例尺)-您只需输入字体大小(以pt为单位),然后键入/.pt。
所以你的代码应该是:
ggplot(data=file,aes(x=V1,y=V3,fill=V2)) +
geom_bar(stat="identity",position="dodge",colour="white") + 
geom_text(aes(label=V2),position=position_dodge(width=0.9),
          hjust=1.5,colour="white", size = 10/.pt) +
theme_bw()

这个转换做的就是Nova上面提到的等同操作。希望对将来寻找这个答案的任何人有所帮助。

1

0

除了接受的答案之外:

查找?.pt,你就会明白14/5的含义以及为什么需要它。


这并没有回答问题。一旦你拥有足够的声望,你就可以评论任何帖子;相反,提供不需要提问者澄清的答案。- 来自评论 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接