最初,dataframe,df是作为字符串排序的,但能够对字母数字向量进行排序:
df <- df[mixedorder(as.character(df$ID)),]
创建桶形图时,(x轴)顺序更改为1 10a 10b 11
,尽管我显式地将顺序更改为1 2 3 4 5
。
发布于 2020-04-26 20:05:47
library(tidyverse)
df <- data.frame(ID=(c("1", "2", "3", "4", "5", "10a", "10b", "11")),
y=c(seq(100,500,100), 150, 155, 180), stringsAsFactors = FALSE)
简单数据的简单修正
df$numId<-1:nrow(df)
ggplot(df, aes(x=reorder(ID,numId), y = y)) +
geom_col() +
labs(x='ID', y='Value')
结果
创建一个函数以使数字值
create_id<-function(x) {
if(!grepl('[a-z]',x,ignore.case = TRUE)) {
return(as.numeric(x))
} else {
letter<-tolower(gsub('[0-9]+',"",x))
letter_value<-which(letters==letter)/100
number<-as.numeric(gsub('[a-z]',"",x)) + letter_value
return(number)
}
}
df<-df %>%
group_by(ID, y) %>%
mutate(nid = round(create_id(ID),3))
ggplot(df, aes(x=reorder(ID,nid), y = y)) +
geom_col() +
labs(x='ID', y='Value')
结果
感谢@user12728748的答复,并提供了dataframe代码。我的答案只是为了满足问题中的ggplot2标记。上面的答案也同样合适。
https://stackoverflow.com/questions/61446119
复制相似问题