Won*_*ifu 44 r ggplot2 geom-bar
我想使用ggplot2和geom_bar创建一个堆积图表.
这是我的源数据:
Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10
Run Code Online (Sandbox Code Playgroud)
我想要一个堆积图表,其中x是等级,y是F1,F2,F3中的值.
# Getting Source Data
sample.data <- read.csv('sample.data.csv')
# Plot Chart
c <- ggplot(sample.data, aes(x = sample.data$Rank, y = sample.data$F1))
c + geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
这是我能得到的.我不确定如何堆叠其余的字段值.
也许我的data.frame格式不好?
ags*_*udy 44
你说 :
也许我的data.frame格式不好?
是的,这是真的.您的数据是宽格式您需要将其设置为长格式.一般来说,长格式更适合变量比较.
reshape2例如,使用以下方法执行此操作melt:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
Run Code Online (Sandbox Code Playgroud)
然后你得到你的条形图:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
Run Code Online (Sandbox Code Playgroud)
但是,使用lattice和barchart智能公式符号,你不需要重塑你的数据,只是这样做:
barchart(F1+F2+F3~Rank,data=dat)
Run Code Online (Sandbox Code Playgroud)
Rol*_*and 41
您需要将数据转换为长格式,不应$在内部使用aes:
DF <- read.table(text="Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10", header=TRUE)
library(reshape2)
DF1 <- melt(DF, id.var="Rank")
library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)

基于 Roland 的回答,使用tidyr将数据从宽到长重塑:
library(tidyr)
library(ggplot2)
df <- read.table(text="Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10", header=TRUE)
df %>%
gather(variable, value, F1:F3) %>%
ggplot(aes(x = Rank, y = value, fill = variable)) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)