2016-05-24 39 views
1

This question解釋瞭如何在圖中添加數學符號。但是,當文本應該存儲在數據框本身中時,這不起作用。這是出現在facet_wrap子圖的小方框中的文本的情況。如何在ggplot facet_wrap文本中添加數學符號?

這是一個可重現的例子。比方說,例如我有T和m³中的這些數據,我想畫一個這樣的情節。

library(ggplot2) 
dtf <- data.frame(year = rep(1961:2010,2), 
        consumption = cumsum(rnorm(100)), 
        item = rep(c("Tea bags","Coffee beans"),each=50), 
        unit = rep(c("T","m^3"),each=50)) 
ggplot(data=dtf)+ 
    geom_line(aes(x=year, y=consumption),size=1) + 
    ylab(expression(paste("Consumption in T or ",m^3))) + 
    scale_x_continuous(breaks = seq(1960,2010,10)) + 
    theme_bw() + facet_wrap(item~unit, scales = "free_y") 

enter image description here

ylab(expression(m^3))顯示正確的單元。我怎麼能在這個方面顯示類似的m³?

+0

也許[此帖](http://stackoverflow.com/問題/ 37399450/parsed-labels-along-one-facet-axis-unparsed-labels-along-the-other)將會很有幫助。 – lmo

回答

4

在您添加標籤labeller = label_parsedfacet_wrap功能,格式化單元爲m^3,並替換空間與~

library(ggplot2) 
dtf <- data.frame(year = rep(1961:2010,2), 
        consumption = cumsum(rnorm(100)), 
        item = rep(c("Tea~bags","Coffee~beans"),each=50), 
        unit = rep(c("T","m^3"),each=50)) 
ggplot(data=dtf)+ 
    geom_line(aes(x=year, y=consumption),size=1) + 
    ylab(expression(paste("Consumption in T or ",m^3))) + 
    scale_x_continuous(breaks = seq(1960,2010,10)) + 
    theme_bw() + facet_wrap(item~unit, scales = "free_y",labeller = label_parsed) 

Example plot from R showing desired solution

+0

感謝它會工作,但我在我的項目名稱中有一個空格,並使用'label_parsed'返回一個錯誤。我在我的問題中用項目名稱中的空格修改了示例。 '解析錯誤(text = as.character(values))::1:8:意外符號1:咖啡豆^'。我看到這已被回答[這裏](http://stackoverflow.com/questions/26269122/label-parsed-of-facet-grid-in-ggplot2-mixed-with-spaces-and-expressions)。 –

+1

嘗試'item = rep(c(「茶袋」,「咖啡〜豆」),每個= 50)' –

+1

好的,謝謝用'〜'替代空格是解決方案。 [答案](http://stackoverflow.com/a/26269348/2641825)建議創建我自己的標籤功能,但它現在似乎已被棄用「現在已經不贊成使用'variable'和'value'參數的標籤。」 –

相關問題