2012-07-27 46 views
6

Có thể có hai truyền thuyết với ggplot2 nhưng dựa trên các tập dữ liệu khác nhau không? Ví dụ, trong đoạn code dưới đây tôi muốn nhận được cả hai truyền thuyết về tình hình đầu tiên và truyền thuyết về tình huống thứ hai trong cùng một hình ảnh. Nỗ lực của tôi (tình huống thứ ba) không hoạt động.hai truyền thuyết dựa trên các tập dữ liệu khác nhau với ggplot2

library(ggplot2) 
library(scales) 

yrng <- range(economics$unemploy) 
xrng <- range(economics$date) 
presidential <- presidential[-(1:3), ] 

# add a fictive factor to the economics dataset 
economics <- cbind.data.frame(economics, col=gl(2, nrow(economics)/2)) 

##################### 
## first situation ## 
##################### 
# first plot with legend 
unemp <- qplot(date, unemploy, data=economics, geom="line", 
       xlab = "", ylab = "No. unemployed (1000s)", colour=col) 
# second plot without legend 
unemp + geom_vline(aes(xintercept = start), data = presidential) 

###################### 
## second situation ## 
###################### 
# first plot without legend 
unemp <- qplot(date, unemploy, data=economics, geom="line", 
       xlab = "", ylab = "No. unemployed (1000s)") 
# second plot with legend 
unemp + 
    geom_rect(aes(NULL, NULL, xmin = start, xmax = end, 
        fill = party), ymin = yrng[1], ymax = yrng[2], 
        data = presidential) + 
    scale_fill_manual(values = alpha(c("blue", "red"), 0.2)) 


##################### 
## third situation ## 
##################### 
# first plot with legend 
unemp <- qplot(date, unemploy, data=economics, geom="line", 
       xlab = "", ylab = "No. unemployed (1000s)", colour=col) 
# second plot with legend 
unemp + 
    geom_rect(aes(NULL, NULL, xmin = start, xmax = end, fill = party), ymin = yrng[1], 
       ymax = yrng[2], data = presidential) + 
    scale_fill_manual(values = alpha(c("blue", "red"), 0.2)) 

Error in data.frame(xmin = 11342, xmax = 14264, fill = "Republican", colour = function (x, : 
    arguments imply differing number of rows: 1, 0 
+1

Mã của bạn lý tưởng nên được dễ dàng để cắt và dán vào R. Vì bạn hiện có các ký tự '>' và '+' không thể thực hiện điều này. Thật khó để xem bạn đang làm gì. –

+0

@ mindless.panda Đây không phải là vấn đề: sao chép mã và sau đó thực hiện "Chỉ dán lệnh" trong bảng điều khiển R :-) –

+0

Bạn giả sử mọi người sử dụng bảng điều khiển R chuẩn. =) –

Trả lời

13

Nói chung, một khi tôi bắt đầu nhận được để âm mưu phức tạp hơn, nó hầu như luôn luôn tốt hơn để ngừng sử dụng qplot và sử dụng ggplot để thay thế. Tôi tìm thấy nó dễ dàng hơn để suy nghĩ về cách tôi là xây dựng cốt truyện lên từng miếng:

ggplot() + 
    geom_line(aes(x=date, y=unemploy, color=col), data=economics) + 
    geom_rect(aes(xmin=start, xmax=end, fill=party), 
      ymin = yrng[1], ymax = yrng[2], data = presidential) + 
    scale_fill_manual(values = alpha(c("blue", "red"), 0.2)) +   
    xlab("") + 
    ylab("No. unemployed (1000s)") 

Điều này cho phép:

plot

Các vấn đề liên quan