R ggplot2-创建指标比例的堆叠直方图,并按总体将其分开
基本上,我有一个数据集,其中有4列包含以下信息:个体(“Ind”)、这些个体所属的地理种群(“Pop”)、属于cluster1的基因组比例和属于cluster2的基因组比例(最后两列加起来等于1) 例如:R ggplot2-创建指标比例的堆叠直方图,并按总体将其分开,r,ggplot2,histogram,R,Ggplot2,Histogram,基本上,我有一个数据集,其中有4列包含以下信息:个体(“Ind”)、这些个体所属的地理种群(“Pop”)、属于cluster1的基因组比例和属于cluster2的基因组比例(最后两列加起来等于1) 例如: Ind <- c(1:20) Pop <- rep(1:2, each = 10) set.seed(234) Cluster1 <- runif(20, 0.0, 1.0) Cluster2 <- 1-Cluster1
Ind <- c(1:20)
Pop <- rep(1:2, each = 10)
set.seed(234)
Cluster1 <- runif(20, 0.0, 1.0)
Cluster2 <- 1-Cluster1
df <- data.frame(Ind, Pop, Cluster1, Cluster2)
我想尝试使用ggplot2
生成一个类似于图中“a”面板的绘图。在这个图中,每个个体都是一个带有每个簇比例的条形图,但x记号是总体,垂直网格将这些总体分开。我知道,如果忽略Pop
并使用melt()
,我可以很容易地生成堆叠的直方图。但是我想知道如何结合Pop
来制作一个优雅的情节,比如上面链接中的情节
谢谢 用
Ind
和Pop
作为id变量,并用facet\u网格绘制它,怎么样?它不是100%像你想要的情节,但通过一些主题调整变得非常接近:
dfm <- melt(df, id = c("Ind", "Pop"))
ggplot(dfm, aes(Ind, value, fill = variable)) +
geom_bar(stat="identity", width = 1) +
facet_grid(~Pop, scales = "free_x") +
scale_y_continuous(name = "", expand = c(0, 0)) +
scale_x_continuous(name = "", expand = c(0, 0), breaks = dfm$Ind) +
theme(
panel.border = element_rect(colour = "black", size = 1, fill = NA),
strip.background = element_rect(colour = "black", size = 1),
panel.margin = unit(0, "cm"),
axis.text.x = element_blank()
)
感谢您的快速回复,这肯定是有希望的,但我举的例子很好,甚至,事实上,我在每个群体中处理的个体数量不均衡,我希望每个geom_条形图的宽度在群体之间保持一致。使用facet\u grid
是一个很好的解决方案,但就我的探索而言,我不能根据每个facet中的个体数量来改变宽度……啊,好的一点,我忽略了这一点。你可以用固定的空格来回避这个问题。我将编辑我的答案以添加代码示例。
dfm <- melt(df, id = c("Ind", "Pop"))
ggplot(dfm, aes(Ind, value, fill = variable)) +
geom_bar(stat="identity", width = 1) +
facet_grid(~Pop, scales = "free_x") +
scale_y_continuous(name = "", expand = c(0, 0)) +
scale_x_continuous(name = "", expand = c(0, 0), breaks = dfm$Ind) +
theme(
panel.border = element_rect(colour = "black", size = 1, fill = NA),
strip.background = element_rect(colour = "black", size = 1),
panel.margin = unit(0, "cm"),
axis.text.x = element_blank()
)
require(ggplot2)
require(reshape2)
require(grid)
Ind <- c(1:30)
Pop <- rep(paste("Pop", 1:3), times = c(5, 15, 10))
set.seed(234)
Cluster1 <- runif(30, 0.0, 1.0)
Cluster2 <- 1-Cluster1
df <- data.frame(Ind, Pop, Cluster1, Cluster2)
dfm <- melt(df, id = c("Ind", "Pop"))
ggplot(dfm, aes(Ind, value, fill = variable)) +
geom_bar(stat="identity", width = 1) +
facet_grid(~Pop, scales = "free_x", space = "free_x") +
scale_y_continuous(name = "", expand = c(0, 0)) +
scale_x_continuous(name = "", expand = c(0, 0), breaks = dfm$Ind) +
theme(
panel.border = element_rect(colour = "black", size = 1, fill = NA),
strip.background = element_rect(colour = "black", size = 1),
panel.margin = unit(0, "cm"),
axis.text.x = element_blank()
)