堆积条形图 [英] Stacked bar chart
问题描述
我想使用 ggplot2 和 geom_bar 创建一个堆积图.
I would like to create a stacked chart using ggplot2 and 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 中的值.
I want a stacked chart where x is the rank and y is the values in 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")
这是我所能做到的.我不确定如何堆叠其余的字段值.
This is as far as i can get. I'm not sure of how I can stack the rest of the field values.
也许我的 data.frame 格式不好?
Maybe my data.frame is not in a good format?
推荐答案
你说:
也许我的 data.frame 格式不好?
Maybe my data.frame is not in a good format?
是的,这是真的.您的数据采用宽格式 您需要将其放入长格式.一般来说,长格式更适合变量比较.
Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.
例如使用 reshape2
,您可以使用 melt
来做到这一点:
Using reshape2
for example , you do this using melt
:
dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
然后你会得到你的条形图:
Then you get your barplot:
ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
geom_bar(stat='identity')
但是使用 lattice
和 barchart
智能公式表示法,您不需要重塑数据,只需这样做:
But using lattice
and barchart
smart formula notation , you don't need to reshape your data , just do this:
barchart(F1+F2+F3~Rank,data=dat)
这篇关于堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!