【问题标题】:Need to adjust ordering of subgroups on geom_bar plot需要调整 geom_bar 图上子组的排序
【发布时间】:2020-02-03 23:35:03
【问题描述】:

需要一些帮助来尝试对该图上的各个条形进行排序,以便它们在“接种前”和“接种后”类别中的顺序相同。我尝试在 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"))

【问题讨论】:

  • 您的问题很可能是count = factor(c(3, 12, 15, 11, 18, 9),))。计数不应该是一个因素。只需count = c(3, 12, 15, 11, 18, 9) 就可以了。
  • 另请注意,在您当前的绘图中,y 轴从 3 到 9 再到 11。显然不正确。同样的问题。

标签: r dataframe ggplot2 visualization geom-bar


【解决方案1】:

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"))

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2017-03-12
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多