R ggplot2 boxplot - 通过函数/矢量值改变盒子宽度 [英] R ggplot2 boxplot - varying box width by a function/vector values

查看:3007
本文介绍了R ggplot2 boxplot - 通过函数/矢量值改变盒子宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个组值的数据框,并且我希望每个类别都有一个boxplot(绘制在一起)。
我希望每个boxplot具有不同的宽度,不是基于每个类别的行数,而是基于列总和。



例如,使用以下data.frame:

 数据<  -  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))

我知道有一种方法可以根据行count,像这样:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ (x =Road Type,y =Happy People Percent)+ $ b $(varwidth = TRUE,alpha = 0.2)+
主题(legend.position =none)+
labs b theme(plot.title = element_text(hjust = 0.5))

但是我想要一个情节与 happyPercentage 的每个 roadType 的箱线图,其宽度基于 drivesCount 在特定道路类型中所占的比例超出了drivesCount总数。



这可能吗?我可以怎么做?

解决方案

可以通过权重美学。
您需要安装 quantreg 软件包才能使用它。我想你可以在那里提供你的函数,我用于演示 drivesCount 列的指数。所以你需要适应这一点。

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


I have a data frame with several groups values, and I would like to have a boxplot per category (drawn together). I want to have each boxplot with a different width, based not on the rows count per category, but on a column sum.

For example, with the following 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))

I know there's a way to have varying width based on rows count, like this:

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

But I want to have a plot with a boxplot for happyPercentage per roadType, with width based on the drivesCount proportion of the specific roadType out of the total drivesCount.

Is that possible? How can I do it?

解决方案

There is the possibility to weight each box plot via the weight aesthetics. You need to have the quantreg package installed to use this. I guess you can just provide your function in there, I used for demonstration an exponent of the drivesCount column. So you need to adapt this a little.

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

这篇关于R ggplot2 boxplot - 通过函数/矢量值改变盒子宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆