【问题标题】:Ordering of bars in grouped barplots using ggplot使用 ggplot 对分组条形图中的条形进行排序
【发布时间】:2021-05-31 14:29:57
【问题描述】:

如何重新排序甲虫的数量,从 0 到 15 以上?我尝试将“甲壳虫的数量”转换为一个因子,但它不起作用。

data<-g
#> Error in eval(expr, envir, enclos): object 'g' not found


#############################################original basic code
ggplot(data,aes(x=Locality.Division))+
  geom_bar(aes(fill=Number.of.Beetle,),position="dodge")+
  facet_wrap(~Building.Age)
#> Error in ggplot(data, aes(x = Locality.Division)): could not find function "ggplot"

############################################wanted to change the order of building age, so convert it to a factor
data.new<-g
#> Error in eval(expr, envir, enclos): object 'g' not found
g$Building.Age<-factor(g$Building.Age,
                              levels = c("Under 5 Years","5-10 Years","Above 10 Years"))
#> Error in factor(g$Building.Age, levels = c("Under 5 Years", "5-10 Years", : object 'g' not found


########################################## run same code by modifying the new name of the data
ggplot(g,aes(x=Locality.Division))+
  geom_bar(aes(fill=Number.of.Beetle,),position="dodge")+
  facet_wrap(~Building.Age)
#> Error in ggplot(g, aes(x = Locality.Division)): could not find function "ggplot"

reprex package (v2.0.0) 于 2021 年 5 月 31 日创建

【问题讨论】:

标签: r ggplot2


【解决方案1】:

诀窍是对列 Number.of.Beetle 的唯一值进行排序并强制转换为因子变量。

data$Number.of.Beetle <- trimws(data$Number.of.Beetle)
lvls <- unique(data$Number.of.Beetle)
lvls <- stringr::str_sort(lvls, numeric = TRUE)
data$Number.of.Beetle <- factor(data$Number.of.Beetle, levels = lvls)

lvls2 <- unique(data$Building.Age)
lvls2 <- lvls2[c(2, 3, 1)]
data$Building.Age <- factor(data$Building.Age, levels = lvls2)

ggplot(data, aes(x = Locality.Division))+
  geom_bar(aes(fill = Number.of.Beetle), position = "dodge")+
  facet_wrap(~ Building.Age)

数据

url <- "https://raw.githubusercontent.com/Sajidha-Mohammed/Beetle-Data/708bf55455c431a1ebf51262899cf74c377dc459/data.csv"
data <- read.csv(url)

【讨论】:

  • @SajidhaMohammed 谢谢,很高兴为您提供帮助。 someone answers您的问题时该怎么办。
猜你喜欢
  • 2022-08-23
  • 2013-02-12
  • 2020-09-01
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
相关资源
最近更新 更多