ggplot2 Tufte线条是否与轴标记相同

7

我已经使用ggplot2和Tufte线条技术多年了,但一直想知道是否有自动化的方法来绘制它们,使它们对应轴标记。

我通常这样绘制它们:

ggplot(mtcars, aes(x=mpg, y=cyl))+
geom_bar(stat = "identity")+
theme_tufte()+
geom_hline(yintercept = c(5,10,15), col="white", lwd=3)

Tufte lines

这里我使用yintercept = c(5,10,15)来指定刻度,但最近我正在构建一个具有可变轴的Shiny应用程序,所以我不能指定固定刻度。

有没有一种方法可以像yintercept = tickmarks这样说,这样我的Shiny应用程序将始终在不预先计算和手动定义轴和Tufte线的情况下工作?

2个回答

6

您可以使用ggplot_build提取刻度线位置作为向量,然后将其传递给geom_hlineyintercept参数:

p <- ggplot(mtcars, aes(x=mpg, y=cyl))+
    geom_bar(stat = "identity")+
    theme_tufte()

tickmarks <- ggplot_build(p)$layout$panel_ranges[[1]]$y.major_source  

p + geom_hline(yintercept = tickmarks, col="white", lwd=3)

谢谢。这正是我正在寻找的。尽管eipi10的解决方案也有效。我不知道为什么这个选项没有被实现在核心函数中。 - magasr

5
这里有一个计算断点位置并将其应用于 scale_y_continuousgeom_hline 的函数:
library(ggthemes)
library(scales)
library(lazyeval)
library(tidyverse)

fnc = function(data, x, y, nbreaks=5, lwd=3, breaks=NULL) {

  if(is.null(breaks)) {
    breaks = data %>% group_by_(x) %>% 
      summarise_(yvar=interp(~ sum(yy), yy=as.name(y)))

    breaks = pretty_breaks(n=nbreaks)(c(0, breaks$yvar))
  }

  ggplot(data, aes_string(x, y)) +
   geom_bar(stat = "identity") +
   theme_tufte() +
   scale_y_continuous(breaks=breaks) +
   geom_hline(yintercept = breaks, col="white", lwd=lwd)
}

现在测试一下这个函数:
fnc(mtcars, "mpg", "cyl") 
fnc(mtcars, "mpg", "cyl", nbreaks=2)

fnc(iris, "Petal.Width", "Petal.Length", breaks=seq(0,80,20))
fnc(iris, "Petal.Width", "Petal.Length", nbreaks=6, lwd=1)

enter image description here


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