2017-04-19 195 views
2

我從我的數據(下面的示例)創建ggplot。我想區分哪些數據點屬於哪個PID。到目前爲止好:改變顏色的調色板中ggplot

violin.murgang <- ggplot(nkv.murgang, aes(x = factor("Murgang"), nkv.murgang$NK)) + 
    geom_violin(color = "black", fill = "darkorange") + 
    ggtitle("NKV Murgang - Einfamilienhaus") + 
    labs(x = "Prozess", y = "Nutzen/Konsten \n Verhälhniss") + 
    stat_summary(geom = "text", fun.y = quantile, 
       aes(label=sprintf("%1.1f", ..y..)), 
       position=position_nudge(x=0.4), size=3) + 
    theme (legend.position = "none") + 
    stat_summary(fun.data = give.n, geom = "text", position=position_nudge(x=-0.4)) + 
    geom_jitter(aes(col = PID), width = 0.35) 
violin.murgang 

的問題是,所有的NKV數據點在不同的色調的藍色只顯現。我想有不同的顏色。我曾嘗試添加此:

scale_colour_brewer(palette="Spectral") 

其產生錯誤:

Error: Continuous value supplied to discrete scale 

我如何能實現具有用於geom_jitter部分不同的顏色?

什麼原因導致錯誤?

謝謝!

+0

我認爲brewer顏色只適用於離散變量。看看'scale_colour_gradient'和'scale_colour_gradient2'。 –

回答

2

如果PID有更多的水平比「光譜」調色板的顏色,你可以嘗試scale_color_distiller,從而延長啤酒的顏色來連續的規模,看到的scale_color_distiller手冊:

# Use distiller variant with continous data 
v <- ggplot(faithfuld) + 
    geom_tile(aes(waiting, eruptions, fill = density)) 
v 
v + scale_fill_distiller() 
v + scale_fill_distiller(palette = "Spectral") 

因此,我們可以嘗試:

ggplot(nkv.murgang, aes(x = factor("Murgang"), nkv.murgang$NK)) + 
    geom_violin(color = "black", fill = "darkorange") + 
    ggtitle("NKV Murgang - Einfamilienhaus") + 
    labs(x = "Prozess", y = "Nutzen/Konsten \n Verhälhniss") + 
    stat_summary(geom = "text", fun.y = quantile, 
       aes(label=sprintf("%1.1f", ..y..)), 
       position=position_nudge(x=0.4), size=3) + 
    theme (legend.position = "none") + 
    geom_jitter(aes(color = PID), width = 0.35) + 
    scale_color_distiller(palette = "Spectral") 

如果你的數據有幾個層面,我們可以使用分立的尺度。 PID是整數,它可以處理離散尺度。您應該先將其轉換成字符或因子:

ggplot(nkv.murgang, aes(x = factor("Murgang"), nkv.murgang$NK)) + 
    geom_violin(color = "black", fill = "darkorange") + 
    ggtitle("NKV Murgang - Einfamilienhaus") + 
    labs(x = "Prozess", y = "Nutzen/Konsten \n Verhälhniss") + 
    stat_summary(geom = "text", fun.y = quantile, 
       aes(label=sprintf("%1.1f", ..y..)), 
       position=position_nudge(x=0.4), size=3) + 
    theme (legend.position = "none") + 
    geom_jitter(aes(color = as.factor(PID)), width = 0.35) + 
    scale_color_brewer(palette = "Spectral") 
+0

謝謝@ mt1022。轉換'PID'就是我所缺少的。現在'scale_color_brewer(palette =「Spectral」)'就像一個魅力! – Danka