我有一个数据集是这样的:
cars trucks suvs
1 2 4
3 5 4
6 4 6
4 5 6
9 12 16
我想画一个柱状图此数据。 目前,我可以做到这一点barplot
:
barplot(as.matrix(autos_data), main="Autos",
ylab= "Total",beside=TRUE, col=rainbow(5))
产生此图:
所以我的问题是:我可以使用GGPLOT2得出这样一个曲线图? 具体来说 - 我怎么使用刻面或其他选项的星期几分割图? 如果是的话,我该如何实现这一目标? 此外,我怎么使用方面产生不同的布局?
这已经被很多次问。 答案是,你必须使用stat="identity"
在geom_bar
告诉ggplot不要总结你的数据。
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")
下面是与tidyr
:
这里最大的问题是,你需要你的数据转换成一个整齐的格式。 我强烈建议你阅读的R用数据科学( http://r4ds.had.co.nz/ ),以让你和与整洁数据和ggplot运行。
在一般情况下,一个好的经验法则是,如果你要输入相同GEOM的多个实例,有可能在你的数据是能够让你把在一切形式的解决方案aes()
函数顶层内ggplot()
在这种情况下,你需要使用gather()
适当地配置您的数据。
library(tidyverse)
# I had some trouble recreating your data, so I just did it myself here
data <- tibble(type = letters[1:9],
repeat_1 = abs(rnorm(9)), repeat_2
=abs(rnorm(9)),
repeat_3 = abs(rnorm(9)))
data_gathered <- data %>%
gather(repeat_number, value, 2:4)
ggplot(data_gathered, aes(x = type, y = value, fill = repeat_number)) +
geom_col(position = "dodge")