I produced this wonderful bar plot (see below). To quickly group my countries by region, I added scale_x_discrete(limits = ORDER )
with some empty limits ""
(specified by ORDER
). It adds empty bars to the plot, which seem to work fine for me, but the axis.ticks
are not consistent. I does not add axis.ticks
(which I prefer), but for the last empty bar, it does. Why that? How to get rid of this single tick?
ORDER <- c("Kiribati", "Marshall Islands", "Palau", "States of Micronesia",
"",
"Micronesia g." ,
"",
"Fiji", "Nauru", "PNG", "Solomon Islands", "Vanuatu",
"",
"Melanesia g.",
"",
"Cook Islands", "Niue", "Samoa", "Tonga", "Tuvalu",
"",
"Polynesia g."
)
ORDER
ggplot(ESA_coun_p ,aes(x=x, y=y))+
geom_col(position="dodge", na.rm=TRUE)+
scale_x_discrete(limits = ORDER )+
coord_flip()
thothal & Romain B. gave some great replies for solving the questions, both with their pro and cons.
@thothal: Your suggestion using labels
instead of limits
make the plot consistent as it adds axis ticks to all empty separation bars. However, it may require hard-coding of some empty extra observations and reordering factors. It also does not distinguish the different groups to well from each other.
@Romain B.: Your suggestion works very well and does distinguish the different groups clearly. However, I ran into difficulties with some more sophisticated plots, a "gap bar plot", which allows to compare values better in case of outliers (see below your example adjusted).
set.seed(10)
test <- data.frame(country = LETTERS[1:12],
region = c(1,1,1,1,2,2,3,4,4,4,5,5),
value = rnorm(12, m = 10))%>%
mutate(value=replace(value, country=='A', 100))
# I'm ordering by <value> here, so in the plot, they'll be ordered as such
test$country <- factor(test$country, levels = test$country[order(test$value)])
######
trans_rate_surf <- 0.02 ##play around, defines cropping of the cut of values
white_space_min_surf <- 20 ##littel bit above the last fully displaied bar
white_space_max_surf<- 80 ##littel bit below the first cropped bar
#####
trans_surf <- function(x){pmin(x,white_space_min_surf) + trans_rate_surf*pmax(x-white_space_min_surf,0)}
yticks_surf <- c(5, 10, 15, 20, 100) ## not within or too close to the white space
##
test$value_t <- trans_surf(test$value)
ggplot(test, aes(x = country, y = value_t)) + geom_bar(stat = 'identity') + coord_flip()+
geom_rect(aes(xmin=0, xmax=nrow(test)+0.6, ymin=trans_surf(white_space_min_surf), ymax=trans_surf(white_space_max_surf)), fill="white")+
scale_y_continuous(limits=c(0,NA), breaks=trans_surf(yticks_surf), labels=yticks_surf)
If I add now + facet_grid(rows = vars(region), scales = "free_y", space = "free_y")
everything is messed up, because xmax=nrow(test)
doesn't fit anymore, but would need to be region sensitive.