R 使用条形图ggplot2堆叠2个数字列
我有这样一个数据框:R 使用条形图ggplot2堆叠2个数字列,r,ggplot2,R,Ggplot2,我有这样一个数据框: df <- data.frame(day=c("one","two","three"),insects=c(50000,25000,12500),ants=c(5000,2500,1250)) day | insects | ants ----------------------- one 50000 5000 two 25000 2500 three
df <- data.frame(day=c("one","two","three"),insects=c(50000,25000,12500),ants=c(5000,2500,1250))
day | insects | ants
-----------------------
one 50000 5000
two 25000 2500
three 12500 1250
结果是(这显然是错误的):
我知道有成百上千的问题在问类似的问题,但我无法解决这个简单的情节。应该有一个简单的解决方案。试试这个:
library(tidyverse)
library(reshape2)
#Melt data
df$day <- factor(df$day,levels = c('one','two','three'),ordered = T)
MD <- melt(df,id.vars = 'day')
#Code
ggplot(data=MD,aes(x=day, y=value, fill=variable))+
geom_bar(stat="identity")+
coord_flip()
库(tidyverse)
图书馆(E2)
#熔化数据
df$day您可能应该使用,其中子组显示在彼此的顶部
library(tidyverse)
library(reshape2)
#Melt data
df$day <- factor(df$day,levels = c('one','two','three'),ordered = T)
MD <- melt(df,id.vars = 'day')
#Code
ggplot(data=MD,aes(x=day, y=value, fill=variable))+
geom_bar(stat="identity")+
coord_flip()