我有以下数据,我想用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
Run Code Online (Sandbox Code Playgroud)
我想要做的是制作条形图并保持条形的顺序(即从开始SC_LTSL_BM ...B_GC_Sp).但ggplot geom_bar的默认行为是对它们进行排序.我怎么能避免这种情况?
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()
Run Code Online (Sandbox Code Playgroud)
目前的数字如下:

Ben*_*Ben 72
你需要告诉ggplot你已经有了一个有序因子,所以它不会自动为你订购.
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")
Run Code Online (Sandbox Code Playgroud)

Ale*_*mas 23
这是一种不修改原始数据但使用scale_x_discrete的方法.来自?scale_x_discrete"使用限制来调整显示的级别(和顺序)"例如:
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)
# plot
library(ggplot2)
ggplot(dat,aes(x=V1,y=V2))+
geom_bar(stat="identity")+
scale_x_discrete(limits=dat$V1)
Run Code Online (Sandbox Code Playgroud)
And*_*own 13
如果您想避免更改原始数据,则可以使用fct_inorderfrom forcats( 的一部分tidyverse) 来保持数据沿 x 轴的原始顺序(而不是更改为字母顺序)。
library(tidyverse)
ggplot(dat, aes(x = fct_inorder(V1), y = V2)) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
输出
另一个选项forcats是手动指定顺序fct_relevel。
ggplot(dat, aes(
x = fct_relevel(
V1,
"SC_LTSL_BM",
"SC_STSL_BM",
"proB_FrBC_FL",
"preB_FrD_FL",
"B_Fo_Sp",
"B_GC_Sp"
),
y = V2
)) +
geom_bar(stat = "identity") +
xlab("Category")
Run Code Online (Sandbox Code Playgroud)
数据
dat <- structure(list(
V1 = c(
"SC_LTSL_BM",
"SC_STSL_BM",
"proB_FrBC_FL",
"preB_FrD_FL",
"B_Fo_Sp",
"B_GC_Sp"
),
V2 = c(16.8275, 17.3914,
122.158, 18.5051, 14.4693, 15.4986)
),
class = "data.frame",
row.names = c(NA, -6L))
Run Code Online (Sandbox Code Playgroud)
您也可以按照此处所述重新排序相应的因子
x$name <- factor(x$name, levels = x$name[order(x$val)])
Run Code Online (Sandbox Code Playgroud)
dplyr 可让您轻松创建row可在 ggplot 中重新排序的列。
library(dplyr)
dat <- read.table("...") %>% mutate(row = row_number())
ggplot(df,aes(x=reorder(V1,row),y=V2))+geom_bar()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47777 次 |
| 最近记录: |