R ggplot带2列的堆叠条形图
出于可解释性的原因,我想为我的数据帧R ggplot带2列的堆叠条形图,r,ggplot2,R,Ggplot2,出于可解释性的原因,我想为我的数据帧df创建一个堆叠条形图,而不必转换数据。我的数据如下所示: #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 pri
df
创建一个堆叠条形图,而不必转换数据。我的数据如下所示:
#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
#代码
年份最终需要进行转换,但更优雅的方法是使用tidyr:
df %>%
select(-total) %>%
gather(type, count, burglaries:robberies) %>%
ggplot(., aes(x=year, y=count, fill=forcats::fct_rev(type))) +
geom_bar(stat="identity")
我做了一些额外的研究,发现库plotly
中的plot\u ly()
函数允许您这样做。以下是有关详细信息的链接:
您的工作方式与ggplot的使用方式背道而驰。ggplot希望您首先转换(融化、收集、整理,不管您想叫它什么)您的数据。所以简单的回答是不,不是真的。
df %>%
select(-total) %>%
gather(type, count, burglaries:robberies) %>%
ggplot(., aes(x=year, y=count, fill=forcats::fct_rev(type))) +
geom_bar(stat="identity")
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')