【问题标题】:Reorder label y axis in ggplot在ggplot中重新排序标签y轴
【发布时间】:2014-07-02 20:48:25
【问题描述】:

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

由于我是新手,我无法显示图像,但它看起来像是 y 轴上的物种列表,并且每个物种都表示一个点,其标准误差条与相应的 x 值(平均值)相对应。物种以木鸭在顶部,高山雨燕在底部(中间按字母顺序排列)。

我想要相反的(顶部是 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 轴的顺序?

【问题讨论】:

  • mydata$species &lt;- factor(mydata$species, levels=c("Alpine Swift","Azure-winged Magpie"...).

标签: r ggplot2


【解决方案1】:
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")

【讨论】:

  • 嗨@jlhoward 如果您想要非字母的 y 轴变量的特定顺序怎么办?比方说 BACDEF...?
【解决方案2】:

尝试将+scale_y_discrete("Species") 更改为+scale_y_discrete("Species", trans = 'reverse')

【讨论】:

    【解决方案3】:

    使用 forcats 包中的 fct_rev() 并遵循 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-04
      • 2022-01-01
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      相关资源
      最近更新 更多