2013-02-17 2 views
1

나는 ggplot2로 데이터 프레임을 그리기 위해 Rpy2를 사용하고 있습니다. 나는 음모에 대한 통계와 각 부가 적 줄거리에 주석하고 싶습니다rpy2의 ggplot으로 서브 플로트에 주석을 달려면 어떻게해야합니까?

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"]()  

을하지만, 실제로 파이썬에서 R의 dataframe에 액세스 할 수 가정하고 어떻게 이러한 상관 관계를 그릴 수 있을까? 감사.

답변

1

해결 방법은 각 샘플에 레이블이있는 데이터 프레임을 만드는 것입니다. 데이터 프레임의 열은 데이터 프레임의 해당 열 이름과 원래 데이터를 일치시켜야합니다. labels_df는 라벨 labels 함유 dataframe가

p += ggplot2.geom_text(data=labels_df, mapping=ggplot2.aes_string(x="1", y="1", mapping="labels"))

플롯되는 라벨 labels_df의 열 이름 : 다음이 플롯 될 수있다. 이 경우 (1,1)은 각 서브 플롯의 레이블 좌표 위치가됩니다.

0

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

작은 사소한 의견 :이 기능이 패싯과 함께 작동하는지 여부는 잘 모르겠습니다.

관련 문제