2017-08-08 15 views
0

我試圖創建一個描述我的學生隨着時間的推移的情節的情節。當我添加顏色時,我無法獲得正確的事件順序。例如,當我使用下面的代碼,我得到事件的正確順序,而不是顏色:如何在向ggplot中的barplot添加顏色時保持事件的順序順序

ggplot(data=activity_timeline, aes(x=" ", y = Total.Time))+ 
    geom_bar(stat="identity", color="black")+ 
    facet_grid(facets=Name~.)+ 
    scale_fill_manual(values = c("red", "blue", "gray", "yellow", "purple", "orange", "green"), 
        name= "The student was doing:", 
        labels = c("Analysis", "Implementation", "None", "Organizing", "Planning", "Research", "Verification"))+ 
    ggtitle("           Time Spent on Problem Solving Activities")+ 
    labs(y = "Time in seconds", x = " ")+ 
    coord_flip()+ 
    theme(legend.position = "bottom", plot.title = element_text(size = 12), 
     strip.text.y = element_text(size=12), 
     strip.text.x = element_text(size=12), 
     axis.title.x=element_text(size=12), 
     legend.text=element_text(size=12), 
     legend.title=element_text(size=12)) 

正確的順序,沒有顏色

Right order, no color

當我添加了色彩選項(第2行),該圖將所有具有相同操作的項目組合在一起。我使用的代碼是:

ggplot(data=activity_timeline, aes(x=" ", y = Total.Time))+ 
    geom_bar(stat="identity", color="black", aes(fill=Action))+ 
    facet_grid(facets=Name~.)+ 
    scale_fill_manual(values = c("red", "blue", "gray", "yellow", "purple", "orange", "green"), 
        name= "The student was doing:", 
        labels = c("Analysis", "Implementation", "None", "Organizing", "Planning", "Research", "Verification"))+ 
    ggtitle("           Time Spent on Problem Solving Activities")+ 
    labs(y = "Time in seconds", x = " ")+ 
    coord_flip()+ 
    theme(legend.position = "bottom", plot.title = element_text(size = 12), 
     strip.text.y = element_text(size=12), 
     strip.text.x = element_text(size=12), 
     axis.title.x=element_text(size=12), 
     legend.text=element_text(size=12), 
     legend.title=element_text(size=12)) 

錯誤的順序,用顏色

Wrong order, with color

我完全新的ggplot和做這一關的,我已經在網上找到的代碼。我試圖使用「時間軸」功能,我無法弄清楚如何使用我的數據。如果任何人有任何關於如何解決此問題的建議,我將不勝感激。

回答

0

如果您希望以特定順序排列堆積條形圖,則可以在數據集中創建一個指示該順序的附加列。否則,我相信geom_bar默認通過它們的填充顏色來排列條。

這裏是爲了說明的樣品數據集:

set.seed(1) 
df <- data.frame(t = rexp(100, rate = 0.1), 
       student = c(rep("s1", 50), rep("s2", 50)), 
       activity = sample(c("a", "b", "c"), 100, replace = T), 
       seq = c(seq(1, 50, 1), seq(1, 50, 1))) 

# without group parameter 
ggplot(df, aes(x = "", y = t, fill = activity)) + 
    geom_bar(stat = "identity", colour = "black") + 
    facet_grid(student~.) + 
    labs(y="time", x = "") + 
    coord_flip() 

plot without group parameter

# with group parameter 
ggplot(df, aes(x = "", y = t, fill = activity, group = seq)) + 
    geom_bar(stat = "identity", colour = "black") + 
    facet_grid(student~.) + 
    labs(y="time", x = "") + 
    coord_flip() 

plot with group parameter

相關問題