2017-10-07 190 views
0

在r中是否有任何函數允許繪製這種散點圖,這些散點圖按組來分隔點?按r中的組繪製散點圖

enter image description here

這是我迄今所做的:

hours = c(0.00 ,-1.78 ,-0.50 ,-2.00 ,-2.80 ,2.00 ,-0.16 ,-0.34 ,1.00 ,1.00 ,2.00 ,-1.34 ,-1.00 ,-1.10 ,-0.43 ,-0.49 ,-0.02 ,-0.91, 0.48 ,2.33 ,1.00 ,0.00 ,1.18 ,1.29 ,-1.07 ,-0.26 ,1.96 ,0.36 ,2.00 ,-0.63 ,-0.80 ,-0.70 ,-2.00 ,1.17 ,0.67 ,-3.00) 
group = c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2) 
df = data.frame(hours,group) 

ggplot(df, aes(group, hours)) + geom_point(shape = 16, size = 5, position = position_jitter(w=0.3,h=0.3)) 

但事實證明怪異:

enter image description here

任何幫助,非常感謝!

+1

什麼是x軸?變體是否增加了抖動? – G5W

+1

你到目前爲止嘗試過什麼?它通常皺起眉頭張貼一張圖的圖片,並說「請爲我做這件事」。你應該看看[製作一個代表例子](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – tbradley

+0

我曾嘗試使用ggplot2並使用抖動,但它並不是我想要的樣子。 – TYL

回答

1

下面是使用汽車數據

library(tidyverse) 
library(ggplot2) 
data(cars) 

cars %>% 
    gather(variable, value) %>% 
    ggplot()+ 
    geom_jitter(aes(x = variable, y = value), width = 0.2, height = 0)+ 
    geom_errorbar(data = cars %>% 
      gather(variable, value) %>% 
      group_by(variable) %>% 
      summarise(value = mean(value)), aes(x = variable, ymin= value, ymax = value))+ 
    geom_hline(aes(yintercept = mean(value)), lty = 2)+ 
    theme_bw() 

enter image description here

只需發佈數據的方法:

ggplot(df)+ 
    geom_jitter(aes(x = as.factor(group), y = hours), width = 0.2, height = 0)+ 
    geom_errorbar(data = df%>% 
        group_by(group) %>% 
        summarise(hours = mean(hours)), aes(x = group, ymin= hours, ymax = hours))+ 
    geom_hline(aes(yintercept = mean(hours)), lty = 2)+ 
    theme_bw() 

enter image description here

+0

嗨,有沒有簡化geom_errorbar代碼的方法?我一直試圖理解它一段時間來調整它。 – TYL

+0

'geom_errorbar'通過設置'ymin == ymax','geom_errorbar'產生一行,輸入'x','ymin','ymax'和其他一些美學。這裏的數據只是按照小組小時計算的平均值,通過'df%>%group_by(group)%>%summarize(小時=平均值(小時))計算''您可以在繪圖之前計算並存儲在一個對象中(如'df_mean' ),只需調用該對象'data = df_mean'。如果你對tidyverse不滿意,你可以使用'aggregate'來完成這樣的任務。 'df_mean = aggregates(hours〜group,data = df,mean)'並在調用'geom_errorbar'時使用這些數據。 – missuse