2017-08-17 95 views
0

我認爲這將是一個容易的,但不是如此。通過分組變量ggplot中的直方圖着色方面

我有我的代碼在一些直方圖方面。他們可以按照標準的顏色主題沒有問題,但如果我想讓他們跟隨一個調色板(對於例如來自不同組的小點的單個散點圖而言工作正常),一切都變得不合時宜。

那裏的紅色進來了?

數據在這裏:https://pastebin.com/0p7SP005

library(ggplot2) 
library(ggthemes) 

ggplot(data = point_list, aes(x = lifetime, 
           y = ..density..)) + 
    geom_histogram() + 
    aes(fill = as.factor(cluster), 
     col = "black") + 
    scale_x_continuous(expand = c(0,0)) + 
    scale_y_continuous(expand = c(0,0)) + 
    coord_cartesian(xlim = c(-2.6,50), 
        ylim = c(0,0.16)) + 
    theme_tufte(base_size = 11, base_family = "Helvetica") + 
    theme(axis.text = element_text(color = "black"), 
      panel.border = element_rect(colour = "black", fill=NA, size=0.7), 
      legend.position = "none") + 
    facet_wrap(~cluster, scales = "free",) + 
    scale_color_brewer(palette = "Set1") 

enter image description here

僅供參考,SET1應該是這樣的: enter image description here

+0

in'aes'它不是col,而是'color' – loki

+2

你的'fill'和'facet_wrap'變量應該是相同的。 'cluster'和'as.factor(cluster)'可能會有所不同。另外,在你的最後一行中,你可能需要'scale_fill_brewer'。 –

+2

哦,這是'scale_fill_brewer'逃脫了我!突然之間一切都很有意義。菜鳥的錯誤。 –

回答

3

我會說明關於爲什麼酒吧的輪廓是紅色的一點,因爲一切已經被覆蓋了。

在您的代碼中,您在審美映射函數中有col = "black",這意味着顏色(用於輪廓)映射到變量。在這種情況下,「黑色」將被解釋爲1級的因素。由於您的代碼還包含scale_color_brewer(palette = "Set1"),因此生成的顏色是Set1調色板中的第一個顏色,即鮮紅色。

(實際字並不重要。如果你有col = "white"或類似的東西,它也就沒有什麼區別的話)

如果你選擇了一個不同的調色板,輪廓顏色會有所不同太。例如:

ggplot(data = point_list, aes(x = lifetime, 
           y = ..density..)) + 
    geom_histogram(size = 3) + # thicker outline to make the color more obvious 
    aes(fill = as.factor(cluster), 
     col = "black") + 
    scale_x_continuous(expand = c(0,0)) + 
    scale_y_continuous(expand = c(0,0)) + 
    coord_cartesian(xlim = c(-2.6,50), 
        ylim = c(0,0.16)) + 
    # theme_tufte(base_size = 11, base_family = "Helvetica") + #commenting this out since I don't have this theme 
    theme(axis.text = element_text(color = "black"), 
     panel.border = element_rect(colour = "black", fill=NA, size=0.7), 
     legend.position = "none") + 
    facet_wrap(~cluster, scales = "free",) + 
    scale_color_brewer(palette = "Set2") 

example

第一種顏色從調色板SET2蒼白上下的綠色(#66c2a5),這是我們在這裏看到。

要獲得黑色輪廓,請按照上述loki的answer指定geom_histogram中的顏色,並確保您此次在aes()之外執行此操作。 :)

+0

這就是它的工作原理。感覺很好,謝謝! –

2

如果你想改變紅色到黑色只是改變你的geom_histogram線:

geom_histogram(color = "black") 

enter image description here