我试图从按字母顺序呈现的分类(Y中的物种)和连续变量(X中)之间的ggplot中获得y轴的标签。但是我在Y轴顶部以字母顺序显示最后一个物种,在底部按字母顺序排列第一个物种。
由于我是新手,我无法显示图像,但它看起来像是y轴上的物种列表,并且每个物种都表示一个点,其标准误差条指向相应的x值(平均值)。这些物种的顶部是Wood Duck,底部是Alpine Swift(中间按字母顺序排列)。
我希望有相反的东西(顶部和底部的种类为“木鸭”)。
我用来绘制图形的命令如下:
# getting data for the error bars
limits<-aes(xmax=mydata$Xvalues+mydata$Xvalues_SD,
xmin=(mydata$Xvalues-mydata$Xvalues_SD))
# plot graph
graph<-ggplot(data=mydata,aes(x = Xvalues, y = species))
+scale_y_discrete("Species")
+scale_x_continuous(" ")+geom_point()+theme_bw()+geom_errorbarh(limits)
我之前尝试订购我的数据集来上传数据并运行图表。 我还尝试使用以下命令重新排序物种因子:
mydata$species <- ordered(mydata$species, levels=c("Alpine Swift","Azure-winged Magpie","Barn Swallow","Black-browed Albatross","Blue Tit1","Blue Tit2","Blue-footed Booby","Collared Flycatcher","Common Barn Owl","Common Buzzard","Eurasian Sparrowhawk","European Oystercatcher","Florida Scrub-Jay","Goshawk","Great Tit","Green Woodhoopoe","Grey-headed Albatross","House Sparrow","Indigo Bunting","Lesser Snow Goose","Long-tailed Tit","Meadow Pipit","Merlin","Mute Swan","Osprey","Pied Flycatcher","Pinyon Jay","Sheychelles Warbler","Short-tailed Shearwater","Siberian Jay","Tawny Owl","Ural Owl","Wandering Albatross","Western Gull1","Western Gull2","Wood Duck"))
但是我得到了相同的图表。
如何更改Y轴的顺序?
答案 0 :(得分:4)
library(ggplot2)
df <- data.frame(x=rnorm(10),Species=LETTERS[1:10])
ggplot(df)+geom_point(aes(x=x,y=Species),size=3,color="red")
df$Species <- factor(df$Species,levels=rev(unique(df$Species)))
ggplot(df)+geom_point(aes(x=x,y=Species),size=3,color="red")
如果你想把y放在其他顺序中,比如说降低x的顺序,那就这样做:
df$Species <- factor(df$Species, levels=df[order(df$x,decreasing=T),]$Species)
ggplot(df)+geom_point(aes(x=x,y=Species),size=3,color="red")
答案 1 :(得分:2)
尝试将+scale_y_discrete("Species")
更改为+scale_y_discrete("Species", trans = 'reverse')
答案 2 :(得分:2)
使用软件包fct_rev()
中的forcats
,并遵循jlhoward的示例:
library(ggplot2)
library(forcats)
df <- data.frame(x = rnorm(10), Species = LETTERS[1:10])
# original plot
ggplot(df) +
geom_point(aes(x = x, y = Species), size = 3, color = "red")
# solution
ggplot(df) +
geom_point(aes(x = x, y = fct_rev(Species)), size = 3, color = "red")