在绘制geom_bar()时避免ggplot对x轴进行排序 [英] Avoid ggplot sorting the x-axis while plotting geom_bar()

查看:3589
本文介绍了在绘制geom_bar()时避免ggplot对x轴进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想用ggplot绘制的以下数据:

I have the following data which I want to plot with ggplot:

SC_LTSL_BM    16.8275
SC_STSL_BM    17.3914
proB_FrBC_FL   122.1580
preB_FrD_FL    18.5051
B_Fo_Sp    14.4693
B_GC_Sp    15.4986

我想要做的是制作条形图并保持条形图的顺序
(即以 SC_LTSL_BM ... B_GC_Sp 开头)。但
ggplot geom_bar的默认行为是对它们进行排序。如何避免这种情况?

What I want to do is to make a bar plot and maintain the order of the bar, (i.e. starting with SC_LTSL_BM ...B_GC_Sp). But the default behavior of ggplot geom_bar is to sort them. How can I avoid that?

  library(ggplot2)
  dat <- read.table("http://dpaste.com/1469904/plain/")
  pdf("~/Desktop/test.pdf")
  ggplot(dat,aes(x=V1,y=V2))+geom_bar()
  dev.off()

目前的数字如下所示:
< img src =https://i.stack.imgur.com/BhGrf.pngalt =在这里输入图片描述>

The current figure looks like this:

推荐答案

你需要告诉ggplot你已经有了一个排序因子,所以它不会自动为你排序。

You need to tell ggplot that you've got an ordered factor already, so it doesn't automatically order it for you.

dat <- read.table(text=
"SC_LTSL_BM    16.8275
SC_STSL_BM    17.3914
proB_FrBC_FL   122.1580
preB_FrD_FL    18.5051
B_Fo_Sp    14.4693
B_GC_Sp    15.4986", header = FALSE, stringsAsFactors = FALSE)

# make V1 an ordered factor
dat$V1 <- factor(dat$V1, levels = dat$V1)

# plot
library(ggplot2)
ggplot(dat,aes(x=V1,y=V2))+geom_bar(stat="identity")

这篇关于在绘制geom_bar()时避免ggplot对x轴进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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