How to plot the x-axis labels and the columns between the marks on the ggplot2 chart?

I prepared MWE and I hope for help in how to set marks and marks in different places on the x axis for a grouped histogram.

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

MWEplot] ([! [Enter image description here

Checkmarks should appear between groups, but the labels should be centered under the grouped columns (as shown in the figure). I tried to set user-defined gaps (as factors) for scale_x_discrete but this only made my scale_x_discrete and labels completely disappear.

Any help is much appreciated!

+7
source share
3 answers

One option is to convert the discrete scale x to continuous to simplify the 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)))) 

enter image description here


2: x marks 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)))) 

enter image description here

Do not ask me about additional grid lines that appeared in 2.25 and 1.75 respectively ...

+6
source

Here is another solution that uses the grid package.

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

Part 1:nTicks /(nTicks+1) identifies the positions in which ticks will be placed.

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

To change the position of ticks, we need to create a gtable

 p2 <- ggplot_gtable(ggplot_build(p1)) 

and find the correct gun (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 due to the different number of partitions.

0
source

Henrik wrote an excellent answer, and I give an explanation of the codes that he used so that readers can understand the code and make some changes if necessary (for example, only make the x-axis labels of an odd number displayed). Explanation here

0
source

Source: https://habr.com/ru/post/1268345/


All Articles