使用以下数据框:
> foo
species density day percent
1 species1 high 1 0.40
2 species1 low 1 0.20
3 species1 medium 1 0.40
4 species2 high 1 0.35
5 species2 low 1 0.10
6 species2 medium 1 0.55
7 species3 high 1 0.35
8 species3 low 1 0.20
9 species3 medium 1 0.45
10 species4 high 1 0.30
11 species4 low 1 0.20
12 species4 medium 1 0.50
13 species1 high 100 0.50
14 species1 low 100 0.40
15 species1 medium 100 0.10
16 species2 high 100 0.40
17 species2 low 100 0.05
18 species2 medium 100 0.55
19 species3 high 100 0.65
20 species3 low 100 0.05
21 species3 medium 100 0.30
22 species4 high 100 0.40
23 species4 low 100 0.20
24 species4 medium 100 0.40
我创建了以下刻面条形图:
require(ggplot2)
foo$density<-factor(foo$density,levels=c('low','medium','high'))
d <- ggplot(foo, aes(x=species, y=percent, fill=density)) +
geom_bar(aes(width=.65), stat="identity") +
facet_grid(. ~ day)
但是,我想合并这些图形以创建单个双因素条形图。在x轴上,每天-1和100-将按物种分组。关于如何创建这个的任何建议?
非常感谢!
答案 0 :(得分:4)
试试这个
foo$species_day <- with(data = foo, expr = paste(species, day))
d <-ggplot(foo, aes(x=species_day, y=percent, fill=density)) +
geom_bar(aes(width=.65), stat="identity")
如果需要,您可以重新排列级别。
答案 1 :(得分:1)
这是另一种将@Joran的建议与您的要求结合在一起的方法。
我已将day
更改为某个因子,但也将默认的x轴标签更改为“Species”。此外,由于density
显然是一个连续因素,我使用了Color Brewer(http://colorbrewer2.org/)的连续色标。您可以通过更改palette
数字或按名称scale_fill_brewer(palette="GnBu")
调用调色板来体验色阶。在Color Brewer网页上找到调色板名称。
foo <- read.table(header=TRUE,
text="species density day percent
1 species1 high 1 0.40
2 species1 low 1 0.20
3 species1 medium 1 0.40
4 species2 high 1 0.35
5 species2 low 1 0.10
6 species2 medium 1 0.55
7 species3 high 1 0.35
8 species3 low 1 0.20
9 species3 medium 1 0.45
10 species4 high 1 0.30
11 species4 low 1 0.20
12 species4 medium 1 0.50
13 species1 high 100 0.50
14 species1 low 100 0.40
15 species1 medium 100 0.10
16 species2 high 100 0.40
17 species2 low 100 0.05
18 species2 medium 100 0.55
19 species3 high 100 0.65
20 species3 low 100 0.05
21 species3 medium 100 0.30
22 species4 high 100 0.40
23 species4 low 100 0.20
24 species4 medium 100 0.40")
foo$density <- factor(foo$density, levels=c("low", "medium", "high"))
foo$day <- factor(paste("Day", foo$day, sep="_"))
library(ggplot2)
d2 <- ggplot(foo, aes(x=day, y=percent, fill=density)) +
theme_bw() +
geom_bar(width=0.95, stat="identity") +
scale_fill_brewer(type="seq", palette=15) +
xlab("Species") +
opts(axis.text.x=theme_text(size=6)) +
facet_grid(. ~ species)
ggsave("barplot_1.png", d2, width=6, height=4)
我还没有解决的一个问题是density
的级别没有以正确的顺序堆叠(对我来说或在@ MYaseen208的答案中)。堆叠在原始帖子中是正确的。有谁知道问题是什么?