分散与ggplot facet_grid同一变量的情节在不同的条件是什么?(scatter plot

2019-08-17 02:01发布

我想用不同的行值点相关数据框一的同一列。 例如,在iris数据帧,我想提出三点散点图比较Petal.Lengthvirginica与的versicolorsetosavirginicaversicolorsetosa 。 我希望它看起来就像一个正常的facet_gridfacet_wrap情节。 例如,我可以这样做:

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

这不是我想要的,因为它绘制Petal.Length自相每个物种的,但我想的情节出现这样的,除非我handcode比较一下其它物种的物种。 如何才能在这做ggplot ? 谢谢。

Answer 1:

这是更好地组数据第一。 我会做这样的事情:

# 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)

这导致:



Answer 2:

你的问题似乎是约上比较落入多个类别很多人衡量一个变量。 鉴于使用你的例子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")



文章来源: scatter plot of same variable across different conditions with ggplot facet_grid?
标签: r ggplot2