Two sided bar plot ordered by date

前端 未结 1 802
傲寒
傲寒 2021-01-06 12:53

I am trying to create a double-sided bar plot like in this answer, but I want to order bars by date and change the x-axis labels to other values (not dates). My data set loo

相关标签:
1条回答
  • 2021-01-06 13:10

    Should to add tricky factor with right levels ordering:

    x = read.csv("data/2015-2016.csv", stringsAsFactors = F)
    x$date = as.Date(x$date, "%d.%m.%Y")
    
    goalsToMisses = data.frame(
      group = c(rep("Goals", nrow(x)), rep("Misses", nrow(x))),
      x = paste(rep(x$rival, 2), "\n(", rep(x$date, 2), ")", sep=""),
      y = c(x$goals, - x$misses),
      stringsAsFactors = F)
    
    matches = unique(goalsToMisses$x)
    goalsToMisses$x = factor(goalsToMisses$x, levels = matches[order(x$date)])
    
    ggplot(goalsToMisses, aes(x = x, y = y, fill = group)) +
      geom_bar(stat="identity", position="identity") +
      ylim(- max(x$goals), max(x$goals)) +
      scale_y_continuous(breaks = seq(- max(x$goals), max(x$goals), 1)) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 15))
    

    0 讨论(0)
提交回复
热议问题