2017-05-19 30 views
2

我真的很喜歡ggplot2ggthemetheme_fivethirtyeight()的所有內容,只是它隱藏了所有的軸標題。用另一個默認主題中的元素替換一個ggplot默認主題元素

如何使用theme_fivethirtyeight()但告訴它從另一個主題繼承軸標題規範?

+3

'theme_fivethirtyeight()+ theme(axis.title = element_text())'。如果在控制檯中鍵入'theme_fivethirtyeight',則會看到'theme_fivethirtyeight()'的代碼。在該代碼中注意'axis.title = element_blank()'語句。你只需要重寫,如上面的代碼。 – eipi10

+0

@Lucas Spangher:下面的例子回答你的問題嗎?如果我誤解了,請告訴我。 – Stan

+0

不 - 它確實!謝謝。對於遲到我感到抱歉 - 我並不期待這麼快的回覆。 –

回答

2

這可以通過很多方式解決。最短的可能是覆蓋element_text參數@ eipi10建議。這將需要爲每個單獨的情節重複。

另一種方法是基於現有主題創建自己的自定義主題。 這種方法的好處是,一旦你完全按照你喜歡的方式獲得它,你就可以重複使用你的主題。以下是使用theme_fivethiryeight()的示例。

的關鍵部分是:

mytheme <- theme_fivethirtyeight() + 
    theme(axis.title = element_text(colour = "black")) 

創建一些虛擬的數據一起工作:

library("ggplot2") 
library("ggthemes") 
# make the results reproducible 
set.seed(5117) 

start_date <- as.Date("2015-01-01") 
end_date <- as.Date("2017-06-10") 

# the by=7 makes it one observation per week (adjust as needed) 
dates <- seq(from = start_date, to = end_date, by = 7) 
val1 <- rnorm(length(dates), mean = 12.5, sd = 3) 

qnt <- quantile(val1, c(.05, .25, .75, .95)) 

mock <- data.frame(myDate = dates, val1) 

p <- ggplot(data = mock, mapping = aes(x = myDate, y = val1)) + 
    geom_line() + 
    geom_point() + 
    geom_hline(yintercept = qnt[1], colour = "red") + 
    geom_hline(yintercept = qnt[4], colour = "red") + 
    geom_hline(yintercept = qnt[2], colour = "lightgreen") + 
    geom_hline(yintercept = qnt[3], colour = "lightgreen") + 
    scale_x_date(date_breaks = "6 month", date_labels = "%b-%y") + 
    theme(axis.text.x = element_text(angle = 90, hjust = 1)) 

這裏是增加供參考原theme_fivethirtyeight()

p + theme_fivethirtyeight()

original theme plot

創建自定義主題:

mytheme <- theme_fivethirtyeight() + 
    theme(axis.title = element_text(colour = "black")) 

應用自定義主題,以原作劇情:

p + mytheme 

custom theme plot

你可以不鍵入主題名稱(「( )「),以瞭解其他可用於自定義的選項。在這裏,我強調了axis.title = element_blank()被替換:

theme_code

+0

非常感謝您提供徹底和完整的答案。回想起來,很明顯 - 對不起 - 但我不確定要替換哪個元素,以及文本元素的其他部分(大小,角度等)會從theme_fivethirtyeight()繼承爲NULL,會發生什麼情況。無論如何,謝謝! –

1

您可以使用%+replace%代替你想要的特定主題元素。對於任何主題,您都可以使用[[來檢索主題元素。所以如果你想axis.title的主題從theme_gdocs你會這樣做:theme_gdocs()[["axis.title"]]。這應該爲你工作:

ggplot(mtcars) + geom_point(aes(hp, cyl)) + 
       theme_fivethirtyeight() %+replace% theme(axis.title = theme_gdocs()[["axis.title"]], 
                 axis.title.x = theme_gdocs()[["axis.title.x"]], 
                 axis.title.y = theme_gdocs()[["axis.title.y"]]) 

enter image description here

我以前theme_gdocs作爲一個例子,但你可以替換成任何你想要的主題。