ggplot - 从数字到分类x-

时间:2016-03-28 14:51:40

标签: r ggplot2 jitter

我需要制作三个平均值+ - SE的图,并为此图添加一些额外的点。 y轴是数字的,x轴应该是分类的。一些附加点在同一类别中具有相同的y值,因此为了获得点偏移,所以它们没有相互覆盖,我将类别更改为值5,10,15,然后将两个点重叠5的x值为4.9和5.1。这很完美 - 但现在我需要在x轴上显示类别。

这是我原来的数据:

Island;Armean;SE;TLR3;TLR4
ST;4,166666667;0,477;1;1
FG;3,666666667;0,715;3;3
SN;1,666666667;0,333;3;2

TLR3和TLR4保存我想要绘制的附加点的值。

qplot(df$Island, df$Armean) + geom_errorbar(aes(x=df$Island, ymin=df$Armean-df$SE, ymax = df$Armean+df$SE), width = 0.25) + geom_point(aes(y=df$TLR3), color ="red") + geom_point(aes(y=df$TLR4), color ="blue") + theme_bw()

上面给出了我需要的情节,但除了我需要将FG的3点和ST的点数相加。

enter image description here

我将数据集更改为:

Island;Armean;SE;TLR3;TLR4
5;4,166666667;0,477;NA;NA
10;3,666666667;0,715;NA;NA
15;1,666666667;0,333;3;2
4,92;NA;NA;1;NA
5,08;NA;NA;NA;1
9,92;NA;NA;3;NA
10,08;NA;NA;NA;3

完美地抵消了这些点,但我不确定如何将旧的类别放回到x轴上?

我可以使用抖动而不是上面的抖动,但我希望这些点与中心线的距离相同,并且只有重叠的点才能被偏移。

enter image description here

1 个答案:

答案 0 :(得分:2)

编辑:Per @ Gregor的评论如下,将qplot更改为ggplot

应该足够简单,以便在X轴上获得旧类别。试试这个:

ggplot(data=df,aes(Island,Armean)) +
  geom_errorbar(aes(x=Island, ymin=Armean-SE, ymax = Armean+SE), width = 0.25) + 
  geom_point(aes(y=TLR3), color ="red") + 
  geom_point(aes(y=TLR4), color ="blue") + theme_bw() + 
  scale_x_continuous(breaks=seq(from=5,to=15, by = 5), labels=c("FG","SN","ST"))

这给出了输出:

enter image description here

如果您不想手动添加标签,可以通过在数据框中添加包含所需级别的其他列来执行此操作。参见:

df <- read.csv(textConnection("Island;Armean;SE;TLR3;TLR4;Island.group
5;4,166666667;0,477;NA;NA;ST
10;3,666666667;0,715;NA;NA;FG
15;1,666666667;0,333;3;2;SN
4,92;NA;NA;1;NA;ST
5,08;NA;NA;NA;1;ST
9,92;NA;NA;3;NA;FG
10,08;NA;NA;NA;3;FG"),header=TRUE,dec=",",sep=";")


 ggplot(data=df,aes(Island,Armean)) +
  geom_errorbar(aes(x=Island, ymin=Armean-SE, ymax = Armean+SE), width = 0.25) + 
  geom_point(aes(y=TLR3), color ="red") + 
  geom_point(aes(y=TLR4), color ="blue") + theme_bw() + 
  scale_x_continuous(breaks=seq(from=5,to=15, by = 5), labels=levels(df$Island.group))

它给出了相同的确切输出:

enter image description here