2016-12-01 127 views
1

爲了解釋的原因,我想創建我的數據框df的堆積條形圖,而不必轉換數據。我的數據是這樣的:2列ggplot堆積條形圖

#Code 
year <- c(1:5) 
burglaries <- c(234,211,201,150,155) 
robberies <- c(12, 19,18,23,25) 
total <- burglaries + robberies 
df <- data.frame(year, burglaries, robberies, total) 

#Output 
print(df) 

    year burglaries robberies total 
1 1  234  12 246 
2 2  211  19 230 
3 3  201  18 219 
4 4  150  23 173 
5 5  155  25 180 

我可以創造我需要通過將我的數據集劇情如下:

df2 <- rbind(
     data.frame(year, "count" = burglaries, "type"="burglaries"), 
     data.frame(year, "count" = robberies, "type"="robberies") 
) 

ggplot(df2, aes(x=year, y=count, fill=type)) + 
    geom_bar(stat="identity") 

enter image description here

有沒有一種方法來創建具有相同的情節數據幀df?雖然我可以轉換數據,但我擔心會讓程序難以跟蹤程序中發生的情況並發現錯誤(我使用的數據集非常大)。

+1

你對ggplot是專爲使用的方式工作。 ggplot _wants_您需要先轉換數據(融化,收集,整理,無論您想要調用它)的數據。所以簡短的回答是否定的,不是真的。 – joran

回答

0

我做了一些額外的研究,並從庫plotly可以讓你做到這一點發現plot_ly()功能。這裏的鏈接以獲得更多信息:plotly website

plot_ly(data=df, x = ~year, y = ~burglaries, type = 'bar', name = 'Burglaries') %>% 
    add_trace(y = ~robberies, name = 'Robberies') %>% 
    layout(yaxis = list(title = 'Count'), barmode = 'stack') 

enter image description here

1

最終需要改造,但更優雅的方式是使用tidyr:

df %>% 
    select(-total) %>% 
    gather(type, count, burglaries:robberies) %>% 
    ggplot(., aes(x=year, y=count, fill=forcats::fct_rev(type))) + 
    geom_bar(stat="identity")