簡體   English   中英

在R中使用facet_grid和ggplot2創建2個面板和2個hline

[英]Creating 2 panels and 2 hlines with facet_grid & ggplot2 in R

這是我第二次嘗試提出問題。 希望這次我能給您一個可重復的例子。

我有一個帶變量DIS和日期的data.frame。 我想用ggplot2繪制data.frame。 日期在x軸上,DIS在y軸上。

我想將其繪制在兩個面板中,但在y軸上具有相同的比例。

小組1:1Q1至4Q4。 面板2:P1到P3。 此外,我想繪制4條水平線:

對照組的下限(在面板1和面板2中應相同)對照組的上限(在面板1和面板2中應相同)面板1的DIS平均值(僅在面板1中可見) )面板2的DIS平均值(應該僅在面板2中可見)我嘗試使用face_grid和geom_hline,但是如您所見,我得到19個面板,水平線在所有面板上均可見。

DIS=c(0.1120, 0.1104, 0.3794, 0.3983, 0.3175, 0.2275, 0.2171, 0.1973, 0.2499, 0.1819, 0.2613, 0.2302, 0.3795, 0.2406, 0.2486, 0.2464, 0.1143, 0.2685, 0.2447)
    Date=c("1Q1","1Q2","1Q3","1Q4","2Q1","2Q2","2Q3","2Q4","3Q1","3Q2","3Q3","3Q4","4Q1","4Q2","4Q3","4Q4","P1","P2", "P3" )

Bush <- data.frame(Date, DIS)

require (ggplot2)

ggplot(Bush, aes(x = Date, y = DIS))+
  geom_point(shape=1)+
  ylim(0,0.5)+
  geom_hline(aes(yintercept=0.07), linetype="dotted")+ #that's the lower limit of the control group
  geom_hline(yintercept=0.19, linetype="dotted")+ # that's the upper limit of the control group
  geom_hline(yintercept=mean(Bush$DIS[1:16]), colour="blue")+ # that's the mean of the values from 1Q1 to 4Q4 - it should only range from 1Q1 until 4Q4 on the x-axis
  geom_hline(yintercept=mean(Bush$DIS[17:19]), colour="blue")+ # that's the mean of the values from P1 to P3 - it should only range from P1 to P3 on the x-axis
  facet_grid(.~ Date, scales="free_x") # it should be grouped in two panels - 1st from 1Q1 to 4Q4, 2nd from P1 to P3

有人可以幫我嗎?

您正在使用x變量。 如果您想要不同的刻面行為,則需要創建一個與您想要看到的行為相匹配的特定變量:

Bush$grp <- rep(c('a','b'),times = c(16,3))

因此,我創建了一個新變量,以您似乎希望它們在面板中一起出現的方式對觀察結果進行分組。 然后,您僅需考慮該變量:

facet_grid(.~ grp, scales="free_x")

為了使水平線出現在單獨的面板中,策略是相同的。 (它總是相同的,這就是ggplot的竅門!)您創建一個數據幀,並帶有一個描述所有內容的變量:

mean_df <- data.frame(grp = c('a','b'),
                      yint = with(Bush,c(mean(DIS[1:16]),mean(DIS[17:19]))))

然后將該數據幀傳遞給geom_hline並將yintercept映射到yint

geom_hline(data = mean_df,aes(yintercept = yint),colour = "blue")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM