【问题标题】:how to overlay boxplot across a scatterplot?如何在散点图上叠加箱线图?
【发布时间】:2020-10-10 19:26:06
【问题描述】:

假数据

set.seed( 123)
x<-rnorm(1000, mean=60,sd=20)
y <-  exp(-10 +  .95*log(x^3)) + rnorm(1000,mean=1,sd=1)
df <- data.frame(x,y)
cls.x <- quantile(df$x, seq(.1, .9, by=.1))
df$x.class <- findInterval(df$x, cls.x)
df$x.class <- as.factor(df$x.class)
head(df)

以下都不行

plot(df$x,df$y,col=3)
par(new=T)
boxplot(y~x.class, data=df,xlab="",ylab="",xaxt="n")

也不是这个

boxplot(y~x.class, data=df,xlab="",ylab="",xaxt="n")
points(df$x,df$y,col=3)

使用 ggplot,我得到的最接近的是使用类似的东西

library(ggplot2)
ggplot(df,aes(x.class,y))+geom_boxplot() + geom_point()

不幸的是,它没有显示轴的真实可变性。 我尝试使用 jitter 选项,但无法强制绘图使用 X 变量的真实可变性

非常感谢任何建议。

Ps:我知道 Rlab 中的 bplot.xy() 函数,但是,该函数不允许我更改箱线图的颜色,或者先绘制点。

library(Rlab)
bplot.xy( x,y,  N=10)
points( x,y, pch=".", col=3, cex=3)

【问题讨论】:

  • 您的意思是不是points(df$x.class, df$y)?您的 x 轴包括 1 到 10(对于 x.class 中的 0-9 因子),但您的 x 范围从 3.8 到 124.8 ......远离屏幕。

标签: r ggplot2 plot scatter-plot boxplot


【解决方案1】:

以下是你想要的吗?

library(ggplot2)

ggplot(df, aes(x, y, fill = x.class)) + 
  geom_point(alpha = 0.10) +
  geom_boxplot(alpha = 0.50)  

【讨论】:

  • 非常感谢@RuiBarradas,这正是我想要实现的 p
  • @ChristianSalas-Eljatib 很高兴为您提供帮助。
【解决方案2】:

您的df$x 从 3 到 124 不等,而您的 x 轴从 1 到 10。在基本图形中,您可以这样做:

plot(jitter(as.integer(df$x.class)), df$y, col=3, type="p", xlab = "", ylab = "", xaxt = "n")
boxplot(y~x.class, data=df,xlab="",ylab="",xaxt="n", add = TRUE)

我添加了jitter 以帮助打破分发。您也可以尝试使用pch=16 使点变成实心,或者使用透明度(例如,col="#aaffaa22" 用于点)。

【讨论】:

  • 谢谢,@r2evans。我想避免抖动。我只是计算 x.class 来绘制箱线图,我知道它们的比例不同。
  • 我建议你 accept Rui 的回答,因为它似乎可以满足你的需求(当然很好!)。在 Stack 网站上,接受是一个很好的步骤和“礼仪”。谢谢! (很高兴你得到了你需要的东西。)
猜你喜欢
  • 2014-03-31
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2018-03-17
  • 2021-05-19
  • 1970-01-01
  • 2021-07-11
  • 2014-07-14
相关资源
最近更新 更多