ggplot2 geom_bar - 如何保持data.frame的顺序

Jon*_*nas 7 r ggplot2 geom-bar

我有一个关于我的数据顺序的问题geom_bar.

这是我的数据集:

  SM_P,Spotted melanosis on palm,16.2
  DM_P,Diffuse melanosis on palm,78.6
  SM_T,Spotted melanosis on trunk,57.3
  DM_T,Diffuse melanosis on trunk,20.6
  LEU_M,Leuco melanosis,17
  WB_M,Whole body melanosis,8.4
  SK_P,Spotted keratosis on palm,35.4
  DK_P,Diffuse keratosis on palm,23.5
  SK_S,Spotted keratosis on sole,66
  DK_S,Diffuse keratosis on sole,52.8
  CH_BRON,Dorsal keratosis,39
  LIV_EN,Chronic bronchities,6
  DOR,Liver enlargement,2.4
  CARCI,Carcinoma,1
Run Code Online (Sandbox Code Playgroud)

我分配以下colnames:

  colnames(df) <- c("abbr", "derma", "prevalence") # Assign row and column names
Run Code Online (Sandbox Code Playgroud)

然后我绘制:

  ggplot(data=df, aes(x=derma, y=prevalence)) + geom_bar(stat="identity") + coord_flip()
Run Code Online (Sandbox Code Playgroud)

情节

为什么ggplot2会随机更改数据的顺序.我希望我的数据顺序与我的一致data.frame.

任何帮助深表感谢!

arv*_*000 11

发布作为答案,因为评论线程变长.您必须使用映射的变量的因子级别指定顺序aes(x=...)

# lock in factor level order
df$derma <- factor(df$derma, levels = df$derma)

# plot
ggplot(data=df, aes(x=derma, y=prevalence)) + 
    geom_bar(stat="identity") + coord_flip()
Run Code Online (Sandbox Code Playgroud)

结果,顺序与df: 在此输入图像描述

# or, order by prevalence:
df$derma <- factor(df$derma, levels = df$derma[order(df$prevalence)])
Run Code Online (Sandbox Code Playgroud)

相同的plot命令给出:

在此输入图像描述


我读了这样的数据:

read.table(text=
"SM_P,Spotted melanosis on palm,16.2
DM_P,Diffuse melanosis on palm,78.6
SM_T,Spotted melanosis on trunk,57.3
DM_T,Diffuse melanosis on trunk,20.6
LEU_M,Leuco melanosis,17
WB_M,Whole body melanosis,8.4
SK_P,Spotted keratosis on palm,35.4
DK_P,Diffuse keratosis on palm,23.5
SK_S,Spotted keratosis on sole,66
DK_S,Diffuse keratosis on sole,52.8
CH_BRON,Dorsal keratosis,39
LIV_EN,Chronic bronchities,6
DOR,Liver enlargement,2.4
CARCI,Carcinoma,1", header=F, sep=',')
colnames(df) <- c("abbr", "derma", "prevalence") # Assign row and column names
Run Code Online (Sandbox Code Playgroud)

  • 如果有人想知道如何处理变量中出现多次级别的数据(即,当_not_ 使用 `stat = "identity"` 而是使用默认计数 stat)时,您可以添加 `unique()`第一步的功能。例如:`df$var &lt;- factor(df$var, levels = unique(df$var))` (3认同)