ggplot散点图排列X轴值

时间:2020-11-06 08:11:41

标签: r ggplot2

您好使用ggplot2图创建图,我想根据我的另一列值修改x轴值,有人可以建议我根据该列值对值进行分组

样本数据

  Names    Values   group
  FLAM_C    20.03965    1
  MER112    20.09371    1
  L1MA10    20.11173    1
   L1PB3    20.20184    1
  LTR78B    20.27392    1
  MLT1H1    20.29194    2
   (TG)n    20.30997    2
  Charlie7  20.58028    2
 MamRep605  20.27392    2
   LTR16A   20.47216    2
  Charlie1b 20.94071    3
   L1PA6    20.29194    3
   MLT1G1   20.68841    4
  LTR67B    20.72445    4
  MER58A    20.94071    4

脚本

library(ggplot2)
df=read.table("test1",sep='\t', header=TRUE)
df = data.frame(df)
head(df)
ggplot(df, aes(y=Values, x =Names, col=group)) +
  geom_point()

test1高于文件中的数据

2 个答案:

答案 0 :(得分:1)

您在这里:

library(tidyverse)
test1<-tribble(~Names,    ~Values,   ~group,
"FLAM_C" ,   20.03965,    1,
"MER112"  ,  20.09371,    1,
"L1MA10"   , 20.11173,    1,
"L1PB3",    20.20184,    1,
"LTR78B",    20.27392,    1,
"MLT1H1",    20.29194,    2,
"(TG)n" ,   20.30997,    2,
"Charlie7",  20.58028,    2,
"MamRep605",  20.27392,    2,
"LTR16A",   20.47216,    2,
"Charlie1b", 20.94071,    3,
"L1PA6",    20.29194,    3,
"MLT1G1",   20.68841,    4,
"LTR67B" ,   20.72445,    4,
"MER58A",    20.94071,    4)


ggplot(test1, 
       aes(y=Values, 
           x =fct_reorder(Names, group),  #if you want to change order of group, use fct_reorder(Names, desc(group))
           col=group)) +
  geom_point()

我不知道为什么要基于组来安排,但是此代码应该对您有用。诀窍是fct_reorder。

答案 1 :(得分:1)

我相信用group分隔点的最好方法是对图进行分面。

library(ggplot2)

ggplot(df1, aes(x = Names, y = Values, color = factor(group))) +
  geom_point() +
  facet_grid(~ group, scales = 'free_x') +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))

如果要对这些组进行重新排序,请强制将正确的级别分解为因数。

然后情节:

library(ggplot2)

df1$group <- factor(df1$group, levels = c(3:4, 1:2))

ggplot(df1, aes(x = Names, y = Values, color = group)) +
  geom_point() +
  facet_grid(~ group, scales = 'free_x') +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))

enter image description here