使用ggplot2的barplot [英] barplot using ggplot2
问题描述
我有这样的数据集:
汽车卡车suvs
1 2 4
3 5 4
6 4 6
4 5 6
9 12 16
<我试图为这些数据绘制条形图。目前,我可以通过 barplot
:
barplot(as。矩阵(autos_data),main =Autos,
ylab =Total,旁边= TRUE,col = rainbow(5))
生成此图:
所以我的问题是:
我可以使用ggplot2来绘制这样的图吗?具体来说 - 我如何使用刻面或其他选项将图形按星期几分割?
如果是,我该怎么做?
此外,我该如何使用facet来产生不同的布局?
这已被多次询问。答案是你必须在 geom_bar
中使用 stat =identity
来告诉ggplot不要总结你的数据。
dat < - read.table(text =
cars cars suvs
1 2 4
3 5 4
6 4 6
4 5 6
9 12 16,header = TRUE,as.is = TRUE)
dat $ day < - factor (Mo,Tu,We,Th,Fr),
levels = c(Mo,Tu,We,Th ))
library(reshape2)
library(ggplot2)
mdat< - melt(dat,id.vars =day)
头(mdat)
ggplot(mdat,aes(variable,value,fill = day))+
geom_bar(stat =identity,position =dodge)
I have a data set like this:
cars trucks suvs
1 2 4
3 5 4
6 4 6
4 5 6
9 12 16
I'm trying to draw a bar chart for this data. Currently, I can do it with barplot
:
barplot(as.matrix(autos_data), main="Autos",
ylab= "Total",beside=TRUE, col=rainbow(5))
Generating this graph:
So my questions are: Can I use ggplot2 to draw such a graph? Specifically - how do I use faceting or other options to split the graph by days of the week? If yes, how do I accomplish that? Additionally, how do I use facet to produce a different layout?
This has been asked many times before. The answer is that you have to use stat="identity"
in geom_bar
to tell ggplot not to summarise your data.
dat <- read.table(text="
cars trucks suvs
1 2 4
3 5 4
6 4 6
4 5 6
9 12 16", header=TRUE, as.is=TRUE)
dat$day <- factor(c("Mo", "Tu", "We", "Th", "Fr"),
levels=c("Mo", "Tu", "We", "Th", "Fr"))
library(reshape2)
library(ggplot2)
mdat <- melt(dat, id.vars="day")
head(mdat)
ggplot(mdat, aes(variable, value, fill=day)) +
geom_bar(stat="identity", position="dodge")
这篇关于使用ggplot2的barplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!