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

独自空忆成欢 提交于 2019-12-01 00:58:06

问题


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(reshape2)

data <- data.frame(name = c("X","Y","Z"), A = c(2,4,6), B = c(1,3,4), C = c(3,4,5))
data <- melt(data, id = 1)

ggplot(data, aes(name,value)) +
  geom_bar(aes(fill = variable), position = "dodge", stat = "identity")

The ticks should appear BETWEEN the groups, but the labels centered below the grouped bars (as they are in the figure). I tried to set user-defined breaks (as factors) for scale_x_discrete but it only made my ticks and labels disappear completely.

Any help is much appreciated!


回答1:


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...




回答2:


Here is another solution which uses grid package.

library(grid)

nTicks <- 2
tickersPosition <- unit(rep(1:nTicks /(nTicks+1), each=2), "native")

Part 1:nTicks /(nTicks+1) identifies positions where ticks will be placed.

p1 <- ggplot(data, aes(name,value)) +
  geom_bar(aes(fill = variable), position = "dodge", stat = "identity") 

To change position of ticks we need to create gtable

p2 <- ggplot_gtable(ggplot_build(p1))

and find the right grob (using str):

p2$grobs[[7]]$children$axis$grobs[[1]]$x <- tickersPosition

After the position is rewritten, we can run

grid::grid.draw(p2)

which will show warnings. This is because of a different number of splits.



来源:https://stackoverflow.com/questions/44255322/how-to-plot-x-axis-labels-and-bars-between-tick-marks-in-ggplot2-bar-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!