2010-08-06 35 views
9

Mi piacerebbe sapere come fare in modo che x e y, nel seguente esempio, i dati siano tracciati sull'asse verticale per ciascun elemento del frame sull'asse orizzontale. Come faccio a farlo con ggplot2?ggplot e R: due variabili nel tempo

x, y = variabili, telaio = AAAAMM

Esempio dati:

df <- structure(list(x = c(0.000892333625290767, 0.0161153931761482, 
0.0188150880795816, 0.0268699106638318, 0.018657330651898, 0.0101065034206662, 
0.00154410447630379), y = c(1.35172948829027, 0.59654026447333, 
0.685835030118683, 0.741545898152761, 1.09653338596292, 0.119448208345102, 
0.104092642854814), frame = c(200912, 201001, 201002, 201003, 
201004, 201005, 201006)), .Names = c("x", "y", "frame"), row.names = c("1", 
"2", "3", "4", "5", "6", "7"), class = "data.frame") 

Sono stato in grado di ottenere un tracciato in una linea, ma sembra che non sta riconoscendo la mia cornice come categorico (non che lo sia, né so come cambiarlo in tale).

p <- ggplot(df, aes(x=frame, y=x)) 
p + geom_line() 

risposta

10

È necessario fondere i dati:

library(reshape2) 
dfm = melt(df, id.vars='frame') 
ggplot(dfm, aes(x=frame, y=value, colour=variable)) + geom_line() 

Questo è ciò che fa al vostro frame di dati:

> dfm 
    frame variable  value 
1 200912  x 0.0008923336 
2 201001  x 0.0161153932 
3 201002  x 0.0188150881 
4 201003  x 0.0268699107 
5 201004  x 0.0186573307 
6 201005  x 0.0101065034 
7 201006  x 0.0015441045 
8 200912  y 1.3517294883 
9 201001  y 0.5965402645 
10 201002  y 0.6858350301 
11 201003  y 0.7415458982 
12 201004  y 1.0965333860 
13 201005  y 0.1194482083 
14 201006  y 0.1040926429 
+0

Grazie, ma questa tratta comunque cornice come una variabile continua, quando dovrebbe essere categoriale –

+1

prima sciogliendo, trasforma il fotogramma in un fattore: df $ frame = factor (df $ frame) – Greg

9

Questa è una risposta piuttosto tardi, ma se volete che il vostro frame data interpretata variabile (mese dell'anno), quindi convertirla in data.

È quindi possibile utilizzare scale_x_date e il pacchetto scales per formattare l'asse x

DF <- melt(df, id.vars = 'frame') 
# note that I am arbitrarily setting each month to be the 15th 
# day of the month, to create a complete date 
DF$date <- as.Date(paste0(as.character(df$frame), '15'), '%Y%M%d') 
library(scales) 
ggplot(DF, aes(x =frame, y = value, colour = variable)) + 
geom_line() + 
scale_x_date('Month', labels = date_format('%b %Y'), breaks = date_breaks('2 months')) 

enter image description here