Domanda

sto usando rpy2-2.0.7 (ho bisogno di questo per funzionare con Windows 7, e la compilazione dei binari per le versioni più recenti rpy2 è un casino) per spingere un dataframe a due colonne in R, creare un paio di strati in ggplot2 , e l'uscita l'immagine in un <.png>.

Ho sprecato innumerevoli ore giocherellare in giro con la sintassi; Sono riuscito a produrre i file di cui avevo bisogno in un certo punto, ma (stupidamente) non se ne accorse e continuato agitarsi in giro con il mio codice ...

Vorrei sinceramente apprezzare alcun aiuto; sotto è una (banale) esempio per la dimostrazione. Grazie mille per il tuo aiuto!!! ~ Eric Burro


import rpy2.robjects as rob
from rpy2.robjects import r
import rpy2.rlike.container as rlc
from array import array

r.library("grDevices")    # import r graphics package with rpy2
r.library("lattice")
r.library("ggplot2")
r.library("reshape")

picpath = 'foo.png' 

d1 = ["cat","dog","mouse"]
d2 = array('f',[1.0,2.0,3.0])

nums = rob.RVector(d2)
name = rob.StrVector(d1)

tl = rlc.TaggedList([nums, name], tags = ('nums', 'name'))
dataf = rob.RDataFrame(tl)

## r['png'](file=picpath, width=300, height=300)
## r['ggplot'](data=dataf)+r['aes_string'](x='nums')+r['geom_bar'](fill='name')+r['stat_bin'](binwidth=0.1)
r['ggplot'](data=dataf)
r['aes_string'](x='nums')
r['geom_bar'](fill='name')
r['stat_bin'](binwidth=0.1)
r['ggsave']()
## r['dev.off']()

* L'uscita è solo un'immagine vuota (181 b).


qui ci sono gli errori più comuni paio R si getta come ho smanettare in ggplot2:

r['png'](file=picpath, width=300, height=300)
r['ggplot']()
r['layer'](dataf, x=nums, fill=name, geom="bar")
r['geom_histogram']()
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()

* RRuntimeError: Errore: Non ci sono strati di trama

r['png'](file=picpath, width=300, height=300)
r['ggplot'](data=dataf)
r['aes'](geom="bar")
r['geom_bar'](x=nums, fill=name)
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()

* RRuntimeError: Errore: quando impostazione estetica, essi possono solo prendere un valore. Problemi: riempimento, x

È stato utile?

Soluzione

Io uso rpy2 esclusivamente tramite modulo poco brillante di Nathaniel Smith chiamato rnumpy (vedi " Link API" nella home page rnumpy). Con questo si può fare:

from rnumpy import *

r.library("ggplot2")

picpath = 'foo.png' 
name = ["cat","dog","mouse"]
nums = [1.0,2.0,3.0]

r["dataf"] = r.data_frame(name=name, nums=nums)
r("p <- ggplot(dataf, aes(name, nums, fill=name)) + geom_bar(stat='identity')")
r.ggsave(picpath)

(sto cercando di indovinare un po 'su come si desidera che il complotto per aspetto, ma si ottiene l'idea.)

Un altro grande vantaggio sta entrando "modalità R" da Python con il modulo ipy_rnumpy. (Vedi il link "integrazione IPython" nella home page rnumpy).

Per le cose complicate, io di solito prototipo R fino a quando ho i comandi complotto elaborato. segnalazione degli errori in rpy2 o rnumpy può diventare piuttosto disordinato.

Ad esempio, il risultato di un'assegnazione (o altro calcolo) è talvolta stampata anche quando dovrebbe essere invisibile. Questo è fastidioso per esempio quando si assegna a grandi frame di dati. Una soluzione rapida è quella di terminare la linea di offendere con una dichiarazione finale che restituisce qualcosa di breve. Per esempio:

In [59] R> long <- 1:20
Out[59] R>
  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
 [19]  19  20

In [60] R> long <- 1:100; 0
Out[60] R> [1] 0

rnumpy.py (Per silenziare alcuni avvisi ricorrenti in rnumpy, ho modificato per aggiungere 'dal avvertimenti importare mettere in guardia' e sostituire ' 'errore di process_revents: ignorati' print' con 'mettere in guardia ( 'errore di process_revents: ignorati' )'. In questo modo, vedo solo l'avviso una volta per sessione.)

Altri suggerimenti

È necessario coinvolgere il dev () prima di spegnerlo, il che significa che si deve stampare () (come JD indovina sopra) prima del lancio dev.off ().

from rpy2 import robjects                          
r = robjects.r                                                                                    
r.library("ggplot2")
robjects.r('p = ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()') 
r.ggsave('/stackBar.jpeg') 
robjects.r('print(p)')
r['dev.off']()

Per rendere un po 'più facile quando si ha a disegnare trame più complesse:

from rpy2 import robjects
from rpy2.robjects.packages import importr
import rpy2.robjects.lib.ggplot2 as ggplot2
r = robjects.r
grdevices = importr('grDevices')
p = r('''
  library(ggplot2)

  p <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
  p <- p + opts(title = "{0}")
    # add more R code if necessary e.g. p <- p + layer(..)
  p'''.format("stackbar")) 
  # you can use format to transfer variables into R
  # use var.r_repr() in case it involves a robject like a vector or data.frame
p.plot()
# grdevices.dev_off()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top