2017-09-04 113 views

回答

1

該圖將作爲基本情況,然後我將介紹如何改變輔助y軸斷裂和標籤:

sapply(c("pipeR", "ggplot2"), require, character.only = TRUE) 

data(swiss) 
swiss %>>% ggplot() + 
    geom_bar(mapping = aes(x = Agriculture, y = Fertility * 30/400), stat = "identity", colour = gray(0.5), fill = gray(0.5)) + 
    geom_line(mapping = aes(x = Agriculture, y = Education)) + 
    geom_point(mapping = aes(x = Agriculture, y = Education), size = 3, shape = 21, fill = "white") + 
    scale_x_continuous() + 
    scale_y_continuous(
    name = expression("Education"), 
    sec.axis = sec_axis(~ . * 400/30 , name = "Fertility"), 
    limits = c(0, 30)) + 
    theme_bw() + 
    theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank() 
) 

enter image description here

更改遊:

swiss %>>% ggplot() + 
    geom_bar(mapping = aes(x = Agriculture, y = Fertility * 30/400), stat = "identity", colour = gray(0.5), fill = gray(0.5)) + 
    geom_line(mapping = aes(x = Agriculture, y = Education)) + 
    geom_point(mapping = aes(x = Agriculture, y = Education), size = 3, shape = 21, fill = "white") + 
    scale_x_continuous() + 
    scale_y_continuous(
    name = expression("Education"), 
    sec.axis = sec_axis(~ . * 400/30 , name = "Fertility", breaks = seq(1,1000,10)), 
    limits = c(0, 30)) + 
    theme_bw() + 
    theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank() 
) 

enter image description here

更改標籤:

swiss %>>% ggplot() + 
    geom_bar(mapping = aes(x = Agriculture, y = Fertility * 30/400), stat = "identity", colour = gray(0.5), fill = gray(0.5)) + 
    geom_line(mapping = aes(x = Agriculture, y = Education)) + 
    geom_point(mapping = aes(x = Agriculture, y = Education), size = 3, shape = 21, fill = "white") + 
    scale_x_continuous() + 
    scale_y_continuous(
    name = expression("Education"), 
    sec.axis = sec_axis(~ . * 400/30 , name = "Fertility", breaks = seq(1,1000,10), labels=rep("x",length(seq(1,1000,10)))), 
    limits = c(0, 30)) + 
    theme_bw() + 
    theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank() 
) 

enter image description here

有用的鏈接:https://whatalnk.github.io/r-tips/ggplot2-secondary-y-axis.nb.html

+1

謝謝你,現在的工作 – samsmith

+0

@samsmith不客氣樂意提供幫助。請點擊綠色複選標記讓其他人知道問題已解決:) –