在Python中使用rpy2向ggplot geom_boxplot输入分位数

2 投票
1 回答
601 浏览
提问于 2025-04-17 18:31

我有一个这样的箱线图:

import os
iris = pandas.read_table(os.path.expanduser("~/iris.csv"),
                         sep=",")
iris["Species"] = iris["Name"]
r_melted = conversion_pydataframe(iris)
p = ggplot2.ggplot(r_melted) + \
    ggplot2.geom_boxplot(aes_string(**{"x": "PetalLength",
                                       "y": "PetalWidth",
                                       "fill": "Species"})) + \
    ggplot2.facet_grid(Formula("Species ~ .")) + \
    ggplot2.coord_flip()
p.plot()

我想问的是:我怎么能改变箱线图中显示的须须(也就是分位数)呢?假设我有一个数据框,可以按行或按列计算分位数,如下所示:

quantiles_df = iris.quantiles(q=0.85, axis=1)

那么我该如何使用 quantiles_df 作为 geom_boxplot 的输入,这样就可以绘制比如从0.2到0.85的分位数,而不是默认的0.25到0.75呢?谢谢。

1 个回答

0

你可以在R语言中从这个开始。首先,计算每种植物(这里是花瓣宽度)在不同种类中的百分位数,然后用这些数据来绘制图表。通过指定 ymin(也就是下须的边界)、lower(箱子的下边界)、middle(箱子中的线)、upper(箱子的上边界)、ymax(上须的边界),并添加 stat = "identity",你就可以自定义箱线图的样式。

library(reshape2)
library(plyr)
library(ggplot2)

dataf <- ddply(iris, .(Species), summarize, quantilesy= quantile(Petal.Width, c(0,0.2, 0.5,0.85,1 )))
dataf$Labels <- rep(c("0%", "20%","50%","85%", "100%"),length(unique(dataf$Species)))

dataf2 <- reshape(dataf , idvar = c("Species"),timevar = "Labels", direction = "wide")
datafmeanx <- ddply(iris, .(Species), summarize, meanx= mean(Petal.Length))
dataf3 <- merge(dataf2,datafmeanx)

b <- ggplot(dataf3 , aes(x=meanx,ymin = `quantilesy.0%`, lower = `quantilesy.20%`, middle = `quantilesy.50%`, upper = `quantilesy.85%`, ymax = `quantilesy.100%`))
b + geom_boxplot(stat = "identity")+ facet_grid(Species~.) + xlab("Mean PetalLength") + ylab("PetalWidth")

编辑:如果你不想使用反引号(见评论):

dataf$Labels <- rep(c("0", "20","50","85", "100"),length(unique(dataf$Species)))

dataf2 <- reshape(dataf , idvar = c("Species"),timevar = "Labels", direction = "wide")
datafmeanx <- ddply(iris, .(Species), summarize, meanx= mean(Petal.Length))
dataf3 <- merge(dataf2,datafmeanx)

b <- ggplot(dataf3 , aes(x=meanx ,ymin = quantilesy.0, lower = quantilesy.20, middle = quantilesy.50, upper = quantilesy.85, ymax = quantilesy.100))
b + geom_boxplot(stat = "identity")+ facet_grid(Species~.) + xlab("Mean PetalLength") + ylab("PetalWidth")

在这里输入图片描述

撰写回答