python - 在python中使用rpy2将分位数输入ggplot geom_boxplot

标签 python r ggplot2 pandas rpy2

我有以下箱线图:

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?谢谢。

最佳答案

您可以在 R 中从这个开始。首先计算变量(此处为 Petal.Width)的每个物种的百分位数,并将这些用于绘图。通过指定 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")

enter image description here

关于python - 在python中使用rpy2将分位数输入ggplot geom_boxplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315247/

相关文章:

Python 套接字模块 : Recv() data response cut off

r - 使用 dplyr 对具有不同长度的个体的时间序列组进行平均

R ggplot 2 图例边框问题

具有字符变量的 R 比例函数

用 R 中的平均组替换缺失值 - 错误 : out of boundaries

r - 使用子集创建高效的每周计算

r - 图像作为图表中的标签?

python - SciKit One-class SVM 分类器训练时间随着训练数据的大小呈指数增长

python - 使用串口通过 Arduino 将多个值发送到 Raspberry

python - 将 x 行子进程标准输出写入文件