简体   繁体   English

在 r 中使用 ggplot2 创建散点图 plot

[英]creating a scatter plot using ggplot2 in r

class_day <- c(1:10)  
control_group <- c(67,72,69,81,73,66,71,72,77,71) 
A_treatment_group <- c(NA,72,77,81,73,85,69,73,74,77)
B_treatment_group <- c(NA,66,68,69,67,72,73,75,79,77) 
class.df<-data.frame(class_day, control_group, A_treatment_group, B_treatment_group)

I tried to convert vecotrs to a table but I am not sure how to include three categories in one plot.我试图将 vecotrs 转换为表格,但我不确定如何在一个 plot 中包含三个类别。

How can I get a scatter plot with three different colors?如何用三个不同的 colors 得到散点图 plot? I would like to set x-axis as class_day above and y axis as scores.我想将 x 轴设置为上面的 class_day,将 y 轴设置为分数。

First, A cleaner way to make a dataframe without the intermediate variables.首先,一种更简洁的方法来制作一个没有中间变量的 dataframe。

You can make this type of chart by pivoting the data into "long" form:您可以通过将数据旋转为“长”形式来制作此类图表:

class.df<-data.frame(class_day = c(1:10),
                     control_group     = c(67,72,69,81,73,66,71,72,77,71), 
                     A_treatment_group = c(NA,72,77,81,73,85,69,73,74,77),
                     B_treatment_group = c(NA,66,68,69,67,72,73,75,79,77) )
library(tidyverse)
class.df %>% 
  pivot_longer(!class_day) %>% 
  ggplot(aes(x=class_day, y=value, color=name))+
  geom_point()

在此处输入图像描述

Here is a version with ggscatter from ggpubr :这是来自ggpubr的带有ggscatter的版本:

library(ggpubr)
library(tidyverse)

class.df %>% 
  pivot_longer(-class_day,
               names_to= "group", 
               values_to = "score") %>% 
  ggscatter(x = "class_day", y = "score", color = "group",
          palette = c("#00AFBB", "#E7B800", "#FC4E07"))

在此处输入图像描述

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

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