使用ggplot facet_grid在不同条件下散布相同变量的图?

3 r ggplot2

我想为具有不同行值的点关联数据帧的相同列.例如,在iris数据帧,我想提出三点散点图比较Petal.Lengthvirginica与那的versicolor,setosavirginicaversicolorsetosa.我希望它看起来像正常facet_gridfacet_wrap情节.例如,我可以这样做:

ggplot(iris) + geom_point(aes(x=Petal.Length, y=Petal.Length)) + facet_grid(~Species)

这不是我想要的,因为它Petal.Length是每个物种对自己的绘图,但我希望情节看起来像这样,除非我手工编码哪个物种与其他物种进行比较.怎么办ggplot呢?谢谢.

bde*_*est 12

您的问题似乎是关于比较多个属于多个类别的单个变量.给出使用iris数据集的示例,散点图可能不是一个有用的可视化.

在这里,我提供了几个单变量可视化ggplot2.我希望其中一个有用:

library(ggplot2)

plot_1 = ggplot(iris, aes(x=Petal.Length, colour=Species)) +
         geom_density() +
         labs(title="Density plots")

plot_2 = ggplot(iris, aes(x=Petal.Length, fill=Species)) +
         geom_histogram(colour="grey30", binwidth=0.15) +
         facet_grid(Species ~ .) +
         labs(title="Histograms")

plot_3 = ggplot(iris, aes(y=Petal.Length, x=Species)) +
         geom_point(aes(colour=Species),
                    position=position_jitter(width=0.05, height=0.05)) +
         geom_boxplot(fill=NA, outlier.colour=NA) +
         labs(title="Boxplots")

plot_4 = ggplot(iris, aes(y=Petal.Length, x=Species, fill=Species)) +
         geom_dotplot(binaxis="y", stackdir="center", binwidth=0.15) +
         labs(title="Dot plots")

library(gridExtra)
part_1 = arrangeGrob(plot_1, plot_2, heights=c(0.4, 0.6))
part_2 = arrangeGrob(plot_3, plot_4, nrow=2)
parts_12 = arrangeGrob(part_1, part_2, ncol=2, widths=c(0.6, 0.4))
ggsave(file="plots.png", parts_12, height=6, width=10, units="in")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Aru*_*run 5

最好先对数据进行分组.我会做这样的事情:

# get Petal.Length for each species separately    
df1 <- subset(iris, Species == "virginica", select=c(Petal.Length, Species))
df2 <- subset(iris, Species == "versicolor", select=c(Petal.Length, Species))
df3 <- subset(iris, Species == "setosa", select=c(Petal.Length, Species))

# construct species 1 vs 2, 2  vs 3 and 3 vs 1 data
df <- data.frame(x=c(df1$Petal.Length, df2$Petal.Length, df3$Petal.Length), 
y = c(df2$Petal.Length, df3$Petal.Length, df1$Petal.Length), 
grp = rep(c("virginica.versicolor", "versicolor.setosa", "setosa.virginica"), each=50))
df$grp <- factor(df$grp)

# plot
require(ggplot2)
ggplot(data = df, aes(x = x, y = y)) + geom_point(aes(colour=grp)) + facet_wrap( ~ grp)
Run Code Online (Sandbox Code Playgroud)

这导致:

在此输入图像描述