堆积条形图

我想使用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格式不正确?


拉风的咖菲猫
浏览 544回答 3
3回答

回首忆惘然

你说 :也许我的data.frame格式不正确?是的,这是真的。您的数据为宽格式,您需要以长格式输入。一般来说,长格式更适合变量比较。使用reshape2例如,你做到这一点使用melt:dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work然后您得到了您的barplot:ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +&nbsp; &nbsp; geom_bar(stat='identity')但是,使用lattice和barchart智能公式符号,你不需要重塑你的数据,只是这样做:barchart(F1+F2+F3~Rank,data=dat)

忽然笑

您需要将数据转换为长格式,并且不应$在内部使用aes:DF <- read.table(text="Rank F1&nbsp; &nbsp; &nbsp;F2&nbsp; &nbsp; &nbsp;F31&nbsp; &nbsp; 500&nbsp; &nbsp; 250&nbsp; &nbsp; 502&nbsp; &nbsp; 400&nbsp; &nbsp; 100&nbsp; &nbsp; 303&nbsp; &nbsp; 300&nbsp; &nbsp; 155&nbsp; &nbsp; 1004&nbsp; &nbsp; 200&nbsp; &nbsp; 90&nbsp; &nbsp; &nbsp;10", header=TRUE)library(reshape2)DF1 <- melt(DF, id.var="Rank")library(ggplot2)ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +&nbsp;&nbsp; geom_bar(stat = "identity")

繁花如伊

基于罗兰的答案,tidyr用于将数据从宽到长整形:library(tidyr)library(ggplot2)df <- read.table(text="Rank F1&nbsp; &nbsp; &nbsp;F2&nbsp; &nbsp; &nbsp;F31&nbsp; &nbsp; 500&nbsp; &nbsp; 250&nbsp; &nbsp; 502&nbsp; &nbsp; 400&nbsp; &nbsp; 100&nbsp; &nbsp; 303&nbsp; &nbsp; 300&nbsp; &nbsp; 155&nbsp; &nbsp; 1004&nbsp; &nbsp; 200&nbsp; &nbsp; 90&nbsp; &nbsp; &nbsp;10", header=TRUE)df %>%&nbsp;&nbsp; gather(variable, value, F1:F3) %>%&nbsp;&nbsp; ggplot(aes(x = Rank, y = value, fill = variable)) +&nbsp;&nbsp; geom_bar(stat = "identity")
打开App,查看更多内容
随时随地看视频慕课网APP