2017-05-07 79 views
7

我現在用了gfplot2的Tufte線多年,但我總是想知道是否有自動繪製它們的方法,所以它們對應於軸的抽搐。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

在這裏,我指定與y截距= C(5,10,15)的蜱,但最近我建造了一座閃亮應用程序改變軸,所以我不能指定固定滴答。

有沒有辦法讓我說出類似於yintercept = tickmarks的內容,這樣我的Shiny應用程序將始終工作,無需預先計算並手動定義軸和Tufte行?

回答

6

您可以使用ggplot_build提取對勾標記位置作爲載體,然後傳遞到yintercept說法geom_hline

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) 
+0

Thanks。這正是我正在尋找的。儘管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