2014-12-20 14 views
13

Đây là những gì tôi có cho đến nay với gói ggvis trong R.Tạo một trục y thứ cho dòng đồ thị với ggvis R

mtcars %>% ggvis(x = ~disp) %>% 
    layer_lines(y = ~wt, stroke := "red") %>% 
    layer_lines(y = ~mpg) %>% 
    add_axis("y", orient = "left", title = "Weight (lb/1000)") %>% 
    add_axis("y", orient = "right", title= "Miles/(US) gallon") %>% 
    add_axis("x", title = "Displacement (cu.in.)") 

tôi không thể có được trục Y còn lại để đại diện cho dữ liệu quy mô wt.

đầu ra này:

enter image description here

Trả lời

12

Tôi giả sử bạn muốn ở bên trái trục y (tức là wt) chia cho 1000:

library(dplyr) #you need this library 
mtcars %>% mutate(wt_scaled=wt/1000) %>% ggvis(x = ~disp) %>% #use mutate from dplyr to add scaled wt 
    layer_lines(y = ~wt_scaled, stroke := "red") %>% #use new column 
    add_axis("y", orient = "left", title = "Weight (lb/1000)" ,title_offset = 50) %>% #fix left axis label 
    scale_numeric("y", domain = c(0, 0.006), nice = FALSE) %>% #align the ticks as good as possible 
    add_axis("y", 'ympg' , orient = "right", title= "Miles/(US) gallon" , grid=F) %>% #remove right y axis grid and name axis 
    layer_lines(prop('y' , ~mpg, scale='ympg')) %>% #use scale to show layer_lines which axis it should use 
    add_axis("x", title = "Displacement (cu.in.)" ) 

và tôi nghĩ rằng đây là những gì bạn muốn:

enter image description here

EDIT:

Nếu bạn chỉ muốn vẽ wt trên trục y trái (nó không phải là rất rõ ràng), sau đó làm mutate(wt_scaled=wt/1) (hoặc loại bỏ đột biến) và biến đổi miền để domain = c(1.5, 5.5)

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