我使用Rpy2用ggplot2绘制数据帧。我画了下面的图:
p = ggplot2.ggplot(iris) +
ggplot2.geom_point(ggplot2.aes_string(x="Sepal.Length", y="Sepal.Width")) +
ggplot2.facet_wrap(Formula("~Species"))
p.plot()
r["dev.off"]()
我想用一些关于情节的统计数据来注释每个子情节。例如,我想计算每个x/y子图之间的相关性,并将其放置在图的右上角。如何做到这一点?理想情况下,我想将数据帧从R转换为Python对象,计算相关性,然后将它们投影到散点上。以下转换不起作用,但这就是我尝试的方法:
# This does not work
#iris_df = pandas.DataFrame({"Sepal.Length": rpy2.robjects.default_ri2py(iris.rx("Sepal.Length")),
# "Sepal.Width": rpy2.robjects.default_ri2py(iris.rx("Sepal.Width")),
# "Species": rpy2.robjects.default_ri2py(iris.rx("Species"))})
# So we access iris using R to compute the correlation
x = iris_py.rx("Sepal.Length")
y = iris_py.rx("Sepal.Width")
# compute r.cor(x, y) and divide up by Species
# Assume we get a vector of length Species saying what the
# correlation is for each Species' Petal Length/Width
p = ggplot2.ggplot(iris) +
ggplot2.geom_point(ggplot2.aes_string(x="Sepal.Length", y="Sepal.Width")) +
ggplot2.facet_wrap(Formula("~Species")) +
# ...
# How to project correlation?
p.plot()
r["dev.off"]()
但假设我真的可以从Python访问R数据帧,我该如何绘制这些相关性?谢谢
解决方案是为绘制的每个样本创建一个带有标签的数据帧。数据帧的列应该将数据帧的相应列名与原始数据相匹配。然后可以用绘制
p += ggplot2.geom_text(data=labels_df, mapping=ggplot2.aes_string(x="1", y="1", mapping="labels"))
其中labels_df
是包含标签的数据帧,labels
是具有要绘制的标签的labels_df
的列名。在这种情况下,(1,1)
将是标签在每个子图中的坐标位置。
我发现@user248237dfsf的答案对我不起作用。ggplot混淆了我正在绘制的数据帧和我用于标签的数据帧。
相反,我使用ggplot2_env=robjects.baseenv'as.environment'
class GBaseObject(robjects.RObject):
@classmethod
def new(*args, **kwargs):
args_list = list(args)
cls = args_list.pop(0)
res = cls(cls._constructor(*args_list, **kwargs))
return res
class Annotate(GBaseObject):
_constructor = ggplot2_env['annotate']
annotate = Annotate.new
现在,我有一个类似于标准注释的东西。
annotate(geom = "text", x = 1, y = 1, label = "MPC")
一个小评论:我不知道这是否适用于面部护理。