如何在ggplot2的顶部面板边框添加线 [英] How to add line at top panel border of ggplot2

查看:724
本文介绍了如何在ggplot2的顶部面板边框添加线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够以编程方式将绿线分配到绘图的最上方.

I would like to be able to programmatically assign a green line to the very top of my plot.

在下面的示例中,我演示了我想要的东西,只是该行位于最底部而不是顶部.理想情况下,我将以类似的方式在theme中完成此操作.

Below I demonstrate in an example what I would like, except the line is at the very bottom, instead of the top. Ideally, I would accomplish this in theme in a similar way.

我尝试用panel.border自己完成顶线,但是它以element_rect作为参数,这意味着绘图的另一侧也将获得绿线.

I have tried to accomplish the top line myself with panel.border but it takes a element_rectas a parameter meaning that the other sides of the plot will also get the green line.

虽然最好使用theme,但我愿意使用geom_hline或其他任何方法.当尝试使用geom_hline实现解决方案时,我遇到了麻烦,即要确定ggplot计算出的y轴的最大值,以将直线干净地放在同一位置,而不管比例在各个图之间的变化如何.根据我的真实数据,y轴的标度变化很大,并且每个图的测量单位都不同.

While it is preferable to use theme, I am open to using geom_hline or anything else. When trying to implement a solution with geom_hline I ran into trouble identifying the max value of the y axis as calculated by ggplot to cleanly put the line in the same place regardless of the scale changing from plot to plot. With my real data, the scale of the y axis varies widely and has different units of measurement from plot to plot.

 library(tidyverse)
 data(mtcars)

 mtcars %>% 
     ggplot(aes(x= mpg, y= disp)) +
     geom_point() +
     theme(axis.line.x= element_line("green", size= 2))

推荐答案

您可以使用annotate并巧妙地使用Inf值来完成此任务.请注意,由于annotate是在绘图内部绘制的,而不是在绘图外部的轴线上的,因此您需要使用两倍粗的线来匹配您对theme所做的操作. Inf值的使用可确保将线条放置在绘图的顶部,无论其单位比例如何.

You could accomplish this with annotate and clever use of Inf values. Note that because annotate is drawing inside the plot and not on the axis line outside of it, you need a line of double thickness to match what you did with theme. The use of Inf values guarantees that the line will be placed at the top of the plot regardless of the scale of its units.

library(tidyverse)
data(mtcars)

mtcars %>% 
  ggplot(aes(x= mpg, y= disp)) +
  geom_point() +
  annotate(geom = 'segment', y = Inf, yend = Inf, color = 'green', x = -Inf, xend = Inf, size = 4) +
  theme(axis.line.x= element_line("green", size= 2))

此外,如果要以编程方式分配线,则可以将对annotate的调用保存在变量中,然后在以后将其简单地添加到绘图中.

Further, you could save the call to annotate in a variable and then simply add this to plots later, if you wanted to assign the line programmatically.

这篇关于如何在ggplot2的顶部面板边框添加线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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