How to plot x-axis labels and bars between tick marks in ggplot2 bar plot?

后端 未结 2 1994
情书的邮戳
情书的邮戳 2021-01-11 12:17

I prepared a MWE and hope for help on how to set ticks and labels at different position on the x-axis for a grouped bar plot.

library(ggplot2)
library(reshap         


        
2条回答
  •  攒了一身酷
    2021-01-11 12:44

    One options would be to convert the discrete x scale to continuous, to facilitate calculation of break positions:

    # numeric version of x values
    data$x <- as.integer(as.factor(data$name))
    

    1. x ticks between groups of bars

    x_tick <- head(unique(data$x), -1) + 0.5
    len <- length(x_tick)
    
    ggplot(data, aes(x = x, y = value, fill = variable)) + 
      geom_col(position = "dodge") +
      scale_x_continuous(breaks = c(sort(unique(data$x)), x_tick),
                         labels = c(sort(unique(data$name)), rep(c(""), len))) +
      theme(axis.ticks.x = element_line(color = c(rep(NA, len + 1), rep("black", len))))
    


    2: x ticks before, between, and after groups of bars

    x_tick <- c(0, unique(data$x)) + 0.5
    len <- length(x_tick)
    
    ggplot(data, aes(x = x, y = value, fill = variable)) + 
      geom_col(position = "dodge") +
      scale_x_continuous(breaks = c(sort(unique(data$x)), x_tick),
                         labels = c(sort(unique(data$name)), rep(c(""), len))) +
      theme(axis.ticks.x = element_line(color = c(rep(NA, len - 1), rep("black", len))))
    

    Don't ask me about the additional grid lines which appeared at 2.25 and 1.75 respectively...

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题