ggplot2 geom_bar-如何保持data.frame的顺序 [英] ggplot2 geom_bar - how to keep order of data.frame

查看:248
本文介绍了ggplot2 geom_bar-如何保持data.frame的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的geom_bar中的数据顺序有疑问.

I have a question concerning the order of data in my 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

我分配了以下名称:

  colnames(df) <- c("abbr", "derma", "prevalence") # Assign row and column names

然后我绘图:

  ggplot(data=df, aes(x=derma, y=prevalence)) + geom_bar(stat="identity") + coord_flip()

为什么ggplot2会随机更改我的数据顺序.我想让我的数据顺序与data.frame保持一致.

Why does ggplot2 randomly change the order of my data. I would like to have the order of my data in align with my data.frame.

非常感谢您的帮助!

推荐答案

发布评论作为答案,因为评论线程越来越长.您必须通过使用aes(x=...)

Posting as answer because comment thread getting long. You have to specify the order by using the factor levels of the variable you map with 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()

结果,与df中的顺序相同:

Result, same order as in df:

# or, order by prevalence:
df$derma <- factor(df$derma, levels = df$derma[order(df$prevalence)])

相同的绘图命令给出:

我读入这样的数据:

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

这篇关于ggplot2 geom_bar-如何保持data.frame的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆