R ggplot2方框图-通过函数/向量值改变方框宽度

R ggplot2方框图-通过函数/向量值改变方框宽度,r,ggplot2,boxplot,R,Ggplot2,Boxplot,我有一个包含多组值的数据框,我希望将每个类别的箱线图绘制在一起。 我希望每个箱线图具有不同的宽度,不是基于每个类别的行数,而是基于列和 例如,使用以下data.frame: Data <- data.frame(roadType = sample(c("Ramp", "Primary Street", "Highway"),100,replace=TRUE), drivesCount = sample(1:100,100,replace=TRUE), ha

我有一个包含多组值的数据框,我希望将每个类别的箱线图绘制在一起。 我希望每个箱线图具有不同的宽度,不是基于每个类别的行数,而是基于列和

例如,使用以下data.frame:

Data <- data.frame(roadType = sample(c("Ramp", "Primary Street", "Highway"),100,replace=TRUE),
         drivesCount = sample(1:100,100,replace=TRUE),
        happyPercentage=sample(c(0,0.25,0.5,0.75,1),100,replace=TRUE))
但是我想要一个每个道路类型的happyPercentage的箱线图,宽度基于特定道路类型的DriveScont在总DriveScont中的比例


可能吗?我该怎么做?

可以通过权重美学对每个方框图进行加权。 您需要安装quantreg软件包才能使用它。我想您可以在这里提供您的函数,我用于演示DriveScont列的指数。所以你需要调整一下

install.packages("quantreg")
ggplot(Data, aes(x=roadType, y=happyPercentage)) +
  geom_boxplot(varwidth = TRUE, alpha=0.2, aes(weight=drivesCount^10)) +
  theme(legend.position="none") +
  labs(x = "Road Type", y = "Happy People Percent") +
  theme(plot.title = element_text(hjust = 0.5))
install.packages("quantreg")
ggplot(Data, aes(x=roadType, y=happyPercentage)) +
  geom_boxplot(varwidth = TRUE, alpha=0.2, aes(weight=drivesCount^10)) +
  theme(legend.position="none") +
  labs(x = "Road Type", y = "Happy People Percent") +
  theme(plot.title = element_text(hjust = 0.5))