如何在使用coord_cartesian时在绘图区域外添加文本? [英] How to add text outside plot region when coord_cartesian is used?

查看:176
本文介绍了如何在使用coord_cartesian时在绘图区域外添加文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在绘图区域的顶部添加一些文字(我的真实数据的p值)。这是一个例子,我试过:

data:

 库(tidyverse)

set.seed(123)
plt< - iris
plt $ Petal.Width< - plt $ Petal.Width + rnorm(nrow(plt ))

plt.text< - plt%>%group_by(Species)%>%summarize(label = max(Petal.Width))

我为面板顶部的 plt.text 保留了sapce,但文本没有出现:

  p < -  ggplot(plt,aes(x = Species,y = Petal.Width) )+ 
geom_violin()+
geom_text(aes(x = Species,y = 4,label = label),
data = plt.text,vjust = 0)+
coord_cartesian(ylim = c(-2,4),expand = 0)+
theme(plot.margin = margin(0.2,0.05,0.05,0.05,'npc'))

< img src =https://i.stack.imgur.com/mIdjw.pngalt =在这里输入图片描述>



按照这篇文章,我试过了:

  gt < -  ggplot_gtable(ggplot_build(p))
gt $ layout $ clip [gt $ layout $ name ==panel]< - off
grid :: grid.draw(gt)

我会做什么,使用 cowplot


$ b

  p <-ggplot(plt,aes(x = Species,y = Petal.Width))+ 
geom_violin()+
coord_cartesian(ylim = c(-2,4),expand = 0 )+
theme_grey()
ann < - ggplot(plt.text,aes(x = Species,y = 0,label = label))+
geom_text()+
theme_void()


library(cowplot)
plot_grid(ann,p,ncol = 1,rel_heights = c(.05,1),align ='v') b


$ b

>


I want to add some text (p values for my real data) on the top of the plot region. Here is a example and what I tried:

data:

library(tidyverse)

set.seed(123)
plt <- iris
plt$Petal.Width <- plt$Petal.Width + rnorm(nrow(plt))

plt.text <- plt %>% group_by(Species) %>% summarise(label = max(Petal.Width))

I reserved sapce for the plt.text on the top of the panel, but the text didn't show up:

p <- ggplot(plt, aes(x= Species, y = Petal.Width)) +
    geom_violin() +
    geom_text(aes(x = Species, y = 4, label = label),
              data = plt.text, vjust = 0) +
    coord_cartesian(ylim = c(-2, 4), expand = 0) +
    theme(plot.margin = margin(0.2, 0.05, 0.05, 0.05, 'npc'))

Following this post, I tried:

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid::grid.draw(gt)

You can see although the text is correctly displayed, the trancated violin plot is also shown in full in the above plot. How can I only show the text outside the plot region and still keep the violin plot trancated?

解决方案

What I'd do, using cowplot:

p <- ggplot(plt, aes(x= Species, y = Petal.Width)) +
    geom_violin() +
    coord_cartesian(ylim = c(-2, 4), expand = 0) +
    theme_grey()
ann <- ggplot(plt.text, aes(x = Species, y = 0, label =label)) +
    geom_text() +
    theme_void()


library(cowplot)
plot_grid(ann, p, ncol = 1, rel_heights = c(.05, 1), align = 'v')

这篇关于如何在使用coord_cartesian时在绘图区域外添加文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆