需要调整geom_bar图上子组的顺序

问题描述 投票:1回答:1

需要一些帮助,以尝试在此绘图上对各个条进行排序,以使它们在“接种前”和“接种后”类别中的顺序相同。我尝试过在ggplot代码和创建数据帧本身的行中手动设置disease.state向量的级别。不知道为什么我会遇到这种麻烦。非常感谢!

df.graph1 <- data.frame(
  exp.period = factor(c("Pre-innoculation", "Pre-innoculation", "Pre-innoculation", "Post-innoculation", "Post-innoculation", "Post-innoculation"), levels=c("Pre-innoculation", "Post-innoculation")),
  disease.state = factor(c("Apparent", "Possible", "NA", "Apparent", "Possible", "NA"), levels = c("NA", "Possible", "Apparent")),
  count = factor(c(3, 12, 15, 11, 18, 9),))

ggplot(df.graph1, aes(x=factor(exp.period, level=c('Pre-innoculation', 'Post-innoculation')), y=count, fill=disease.state)) + 
  geom_bar(stat="identity", position=position_dodge(), colour="black") + 
  theme_classic() + 
  xlab("Experimental Period") + 
  ylab("") +
  guides(fill=guide_legend(title="Disease State"))
r dataframe ggplot2 visualization geom-bar
1个回答
0
投票

df.graph1$disease.state=factor(df.graph1$disease.state,levels = c("NA","Possible","Apparent"),ordered = T) #set order of bars

df.graph1$observations=as.numeric(as.character(df.graph1$count)) #convert count to numeric (try what happens, if you only convert to numeric, without converting to character first)

ggplot(df.graph1, aes(x=exp.period, y=observations,
                      fill=disease.state)) + 
  geom_col(position=position_dodge(), colour="black") + 
  theme_classic() + 
  xlab("Experimental Period") + 
  ylab("") +
  guides(fill=guide_legend(title="Disease State"))

© www.soinside.com 2019 - 2024. All rights reserved.