2015-06-09 19 views
6

使用geom_pointposition_jitterdodge只在設置填充美學時纔有效。我不明白爲什麼這應該是!r/ggplot - 使用position_jitterdodge沒有填充美學

此命令

library(ggplot2) 
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
     aes(x = cut, y = carat, color = clarity)) + 
    geom_point(shape = 21, position = position_jitterdodge()) 

產生一個錯誤:

Error: position_jitterdodge requires the following missing aesthetics: fill 

這工作,雖然:

ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
     aes(x = cut, y = carat, fill = clarity)) + 
    geom_point(shape = 21, position = position_jitterdodge()) 

enter image description here

只需供給NA值補是不是一個可行的解決方法:

ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
     aes(x = cut, y = carat, color = clarity, fill=NA)) + 
    geom_point(shape = 21, position = position_jitterdodge()) 

> Error in seq.default(h[1], h[2], length = n) : 
    'to' cannot be NA, NaN or infinite 

但如果你指定的任意常數(原諒可怕的結果),它的工作原理:

ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
     aes(x = cut, y = carat, color = clarity, fill='constant')) + 
    geom_point(shape = 21, position = position_jitterdodge()) 

enter image description here

如何使用抖動任何想法/閃避沒有指定填充? (即僅着色點)

編輯:繼@ @ joran的評論,我想疊加在盒形圖上的點。由於人們不一定會使用fill來區分箱形圖,如果geom_point(position=position_jitterdodge())容納沒有fill的圖,這將是很好的。也許目前不可能,雖然...

#This doesn't work: 
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
     aes(x = cut, y = carat, color = clarity)) + 
    geom_boxplot() + 
    geom_point(shape = 21, position = position_jitterdodge()) 

#This does, although obviously no one wants a plot like this 
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
     aes(x = cut, y = carat, color = clarity, fill='constant')) + 
    geom_boxplot() + 
    geom_point(shape = 21, position = position_jitterdodge()) 

#This is way it's intended to work, but marries you to 'fill' 
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
     aes(x = cut, y = carat, fill = clarity)) + 
    geom_boxplot() + 
    geom_point(shape = 21, position = position_jitterdodge()) 
+2

這是不是一個錯誤。這個_feature_的起源是特定的需求,將點放置在已經通過'fill'閃退的閃避箱子圖上(這在''position_jitterdodge'的文檔中明確提到過]。我同意如果沒有盒子的情況下它會很好,但這只是一個意料之外的用例,而不是一個錯誤。 – joran

+0

實際上,疊加在箱形圖上正是我想要做的,但在我的情況下,箱形圖已經被顏色躲閃。我從上面最小的例子中省略了這個,它看起來並不相關,但我將它添加回來。 – arvi1000

+2

我可以通過分叉ggplot2並簡單地編輯'position_jitterdodge'來使用'colour'而不是fill來工作。但我不確定你會如何編寫這個函數(至少,如何編寫它)來處理這兩種情況。 – joran

回答

4

好的,這是我的解決方法。指定fill用(在我的情況color)你真的想要的審美一起,然後空出充滿scale_fill_manual

我產生了不同的假數據集更類似於我的實際使用情況下,由於上述ISN作爲指定的鑽石數據」噸真的一個很好的候選人盒+分

my_dat <- data.frame(class=factor(rep(1:2, 600)), 
        y=rnorm(1200)), 
        x=rep(letters[1:3], each=400)) 

ggplot(my_dat, aes(x=x, y=y, fill=class, color=class)) + 
    geom_boxplot(outlier.shape = NA) + 
    geom_point(shape = 21, alpha = 0.5, position=position_jitterdodge()) + 
    scale_fill_manual(values = rep(NA, 2)) 

enter image description here