gpt4 book ai didi

在ggplot中重新排序标签y轴

转载 作者:行者123 更新时间:2023-12-03 22:56:14 25 4
gpt4 key购买 nike

我试图从分类(Y 中的物种)和按字母顺序显示的连续变量(X 中)之间的 ggplot 中获得 y 轴的标签。但是我在 Y 轴顶部按字母顺序显示最后一个物种,在底部按字母顺序显示第一个物种。

由于我是新手,我无法显示图像,但它看起来像 y 轴上的物种列表,每个物种都表示一个点,其标准误差条与相应的 x 值(平均值)。物种的顶部为 Wood Duck,底部为 Alpine Swift(中间按字母顺序排列)。

我想要相反的类型(顶部为 Alpine Swift,底部为 Wood Duck)。

我用来绘制图形的命令如下:

# 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 轴的顺序?

最佳答案

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

关于在ggplot中重新排序标签y轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23660725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com