2012-11-16 94 views
3

我想問一下,是否可以用stat_sum繪製的每個點與該點表示的觀察值的百分比(即比例)進行標記。理想情況下,我希望標籤採用百分比格式而不是小數。ggplot2 stat_sum:使用百分比標記點

非常感謝您的時間。

編輯:最小的可重複的例子

library("ggplot2") 
library("scales") 

ggplot(diamonds, aes(x = cut, y = clarity)) + 
    stat_sum(aes(group = 1)) + 
    scale_size_continuous(labels=percent) 

Image of the resulting plot

所以我的問題是,如何(如果可能)標記每個與他們的「託」百分比值的彙總點。

+0

也許你可以給一些(可重複)示例代碼? – ROLO

+0

道歉,我無法分享我正在使用的數據,但是我生成的情節與文檔中的完全相同:http://docs.ggplot2.org/current/stat_sum.html。第二個示例圖代表我擁有的。我希望能夠使用它們的prop值來標記每個彙總點,儘管理想情況下是以百分比格式。我希望這有助於闡述。 – Harry

+1

@Harry你的問題一直沒有答案16個小時,雖然它應該很容易解決,可能是因爲你沒有提供一個最小可重現的例子。我可以建議你製作一些僞造的數據(一小套)和必要的支持代碼的最低限度,然後將它們添加到你的問題。作爲另一個新手把它從我身上拿走,這會提高你獲得答案的機會。請參閱http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – SlowLearner

回答

9

有幾個選項。我會假設這個圖例是不需要的,因爲這些點是用百分比計數標記的。

一種選擇是添加另一個stat_sum()函數,其中包含標籤審美和「文本」幾何。例如:

library("ggplot2") 

ggplot(diamonds, aes(x = cut, y = clarity, group = 1)) + 
    stat_sum(geom = "point", show.legend = FALSE) + 
    stat_sum(aes(label = paste(round(..prop.. * 100, 2), "%", sep = "")), 
       size = 3, hjust = -0.4, geom = "text", show.legend = FALSE) 

或者,可能不需要這些點。標籤可以做所有的工作 - 顯示位置和大小:

ggplot(diamonds, aes(x = cut, y = clarity, group = 1)) + 
    stat_sum(aes(label = paste(round(..prop.. * 100, 2), "%", sep = "")), 
       geom = "text", show.legend = FALSE) + 
    scale_size(range=c(2, 8)) 

有時它是更容易地創建外ggplot的彙總表:

library(plyr) 
df = transform(ddply(diamonds, .(cut, clarity), "nrow"), 
     percent = round(nrow/sum(nrow)*100, 2)) 

ggplot(df, aes(x = cut, y = clarity)) + 
    geom_text(aes(size = percent, label = paste(percent, "%", sep = "")), 
        show.legend = FALSE) + 
    scale_size(range = c(2, 8)) 

enter image description here

+0

多麼美妙的答案;非常感謝。 – Harry