简体   繁体   English

在R中按组绘制散点图

[英]Plotting scatter plot by groups in r

Is there any function in r that allows the plotting of this kind of scatter plots, which separates the dots by group? r中是否有任何函数可以绘制这种散点图,从而将点按组分开?

在此处输入图片说明

Here is what I have done so far: 到目前为止,这是我所做的:

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))

But it turns out weird: 但是结果却很奇怪:

在此处输入图片说明

Any help is really appreciated! 任何帮助都非常感谢!

Here is an approach using cars data 这是使用汽车数据的方法

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()

在此处输入图片说明

With just posted data: 带有刚刚发布的数据:

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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM