【问题标题】:Inputting quantiles to ggplot geom_boxplot using rpy2 in python在python中使用rpy2将分位数输入ggplot geom_boxplot
【发布时间】:2013-02-25 06:02:48
【问题描述】:

我有以下箱线图:

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

【问题讨论】:

  • 你能发布你的完整代码吗?您正在导入pandas。还有什么?

标签: python r ggplot2 pandas rpy2


【解决方案1】:

您可以在 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")

【讨论】:

  • 能解释一下dataf3的最终格式吗?那些反引号在做什么?将那些ddply 调用翻译成熊猫会很困难。我想应该使用groupby,但我发现这种格式非常神秘,所以很难翻译成python
  • 因为“%”是 ggplot 中的非法字符,所以我必须将名称括在反引号中。如果你去掉“%”符号,你可以制作没有刻度的图。我添加了它。尝试在 R 中运行它以查看 dataf3 的最终格式。行是物种,计算的分位数和平均值是列,因此数据框有 3 行和 7 列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 2020-11-06
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多