Reputation: 83
I need to change x-axis ticks to be between sets of dodged bars in a ggplot barplot that has been rotated using coord flip.
This question has a solution that works brilliantly up to the point of coord_flip() How to plot x-axis labels and bars between tick marks in ggplot2 bar plot?
but then the code puts tick marks at the x(now Y) axis labels AS WELL as between the groups.... can anyone explain why and what to do about it....
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))))+coord_flip()
Upvotes: 1
Views: 55
Reputation: 123938
When using coord_flip
you have to set axis.ticks.y
in theme
:
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 <- reshape2::melt(data, id = 1)
data$x <- as.integer(as.factor(data$name))
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.y = element_line(color = c(
rep(NA, len - 1),
rep("black", len)
))) +
coord_flip()
Or as a second option, get rid of coord_flip
by switching x
and y
and setting orientation="y"
in geom_col
:
ggplot(data, aes(y = x, x = value, fill = variable)) +
geom_col(position = "dodge", orientation = "y") +
scale_y_continuous(
breaks = c(sort(unique(data$x)), x_tick),
labels = c(sort(unique(data$name)), rep(c(""), len))
) +
theme(
axis.ticks.y = element_line(
color = c(rep(NA, len - 1), rep("black", len))
)
)
Upvotes: 3