R语言 如何确保geom_text的所有字母都适合ggplot2框

g6baxovj  于 2023-06-03  发布在  其他
关注(0)|答案(1)|浏览(297)

简化问题如下:

library(dplyr)
library(ggplot2)

data.frame(x=c(1,10,100,1000,10000), nms = c("A","B","C","D","E")) %>% 
  ggplot(aes(x=x, y=nms)) + 
  geom_bar(stat = "identity") + 
  geom_text(aes(label = x), 
            vjust = 0.5, hjust = -0.1, color = "gray")

如图所示,对于某些值,geom_text的数字不显示。我手动设置x轴的限制,例如添加+ scale_x_continuous(limits=c(0,11000))。但这似乎不是一个好的做法,因为上限的值是随机设置的。将上限放大例如10%max(x)*1.1不是一个解决方案,因为10%是一个随机数,特别是如果期望对数转换可以添加(或不添加)到x尺度,这取决于用于相同可视化的不同数据集的特定值,因此它不考虑打印文本标签的宽度。
所以我的问题是添加这些geom_text几何图元的正确解决方案是什么?

cczfrluj

cczfrluj1#

你可以使用expand参数代替手工定义限制。默认值是每边5%,所以expand = expansion(mult = c(0.05, 0.1))应该可以做到这一点。

data.frame(x=c(1,10,100,1000,10000), nms = c("A","B","C","D","E")) %>% 
    ggplot(aes(x=x, y=nms)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label = x), 
              vjust = 0.5, hjust = -0.1, color = "gray") + 
    scale_x_continuous(expand = expansion(mult = c(0.05,0.1)))

我们可以使用hjust = "inward"使文本“向内”

library(dplyr)
library(ggplot2)

data.frame(x=c(1,10,100,1000,10000), nms = c("A","B","C","D","E")) %>% 
  ggplot(aes(x=x, y=nms)) + 
  geom_bar(stat = "identity") + 
  geom_text(aes(label = x), 
            vjust = 0.5, hjust = "inward", color = "gray")

或者我们可以用coord_cartesian(clip = 'off')关闭clip

data.frame(x=c(1,10,100,1000,10000), nms = c("A","B","C","D","E")) %>% 
ggplot(aes(x=x, y=nms)) + 
  geom_bar(stat = "identity") + 
  geom_text(aes(label = x), 
            vjust = 0.5, hjust = -0.1, color = "gray")+
  coord_cartesian(clip = 'off')

可能需要调整打印边距。

data.frame(x=c(1,10,100,1000,10000), nms = c("A","B","C","D","E")) %>% 
  ggplot(aes(x=x, y=nms)) + 
  geom_bar(stat = "identity") + 
  geom_text(aes(label = x), 
            vjust = 0.5, hjust = -0.1, color = "gray") +
  theme(plot.margin = unit(c(1,1,1,1),'cm')) +
  coord_cartesian(clip = 'off')

创建于2023-05-26带有reprex v2.0.2

相关问题