2016-12-01 134 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")