我想使用ggplot2和geom_bar创建堆积图表。
这是我的源数据:
Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10
我想要一个堆积图表,其中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")
这是我能得到的。我不确定如何堆叠其余的字段值。
也许我的data.frame格式不好?
答案 0 :(得分: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")
答案 1 :(得分:41)
你说:
也许我的data.frame格式不好?
是的,这是真的。您的数据采用广泛格式您需要将其设置为长格式。一般来说,长格式更适合变量比较。
例如,使用reshape2
,您可以使用melt
执行此操作:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
然后你得到了你的情节:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
但是使用lattice
和barchart
智能公式表示法,您不需要重塑数据,只需这样做:
barchart(F1+F2+F3~Rank,data=dat)
答案 2 :(得分:4)
以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")
答案 3 :(得分:3)
您需要melt
数据框才能将其转换为所谓的长格式:
require(reshape2)
sample.data.M <- melt(sample.data)
现在,您的字段值由其自己的行表示,并通过变量列进行标识。现在可以在ggplot美学中使用它:
require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")
您可能还有兴趣使用构面显示多个图表,而不是堆叠:
c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")