Reputation: 3311
When using dodged bars in a ggplot with discrete x axis, they are centered around the x ticks. As a consequence, also the vertical grid lines pass along the tick in the middle of the group of bars.
I would like instead to have grid lines between the groups of bars. This is especially useful in cases like the one shown before, in which bars are sparse and is not immediate which group each bar belongs to.
Here's the code (without ordering of the x, which is not related and long to write):
library(ggplot)
library(dplyr)
structure(list(Reparto = c("Oncologia medica", "Centro trapianti",
"Chirurgia epatobiliare", "Dh oncologico", "Radioterapia", "Chirurgia",
"Chirurgia oncologica", "Gastroenterologia", "Radiologia", "Oncologia medica",
"Centro trapianti", "Chirurgia epatobiliare", "Dh oncologico",
"Radioterapia", "Chirurgia", "Chirurgia oncologica", "Gastroenterologia",
"Radiologia", "Oncologia medica", "Centro trapianti", "Chirurgia epatobiliare",
"Dh oncologico", "Radioterapia", "Chirurgia", "Chirurgia oncologica",
"Gastroenterologia", "Radiologia", "Oncologia medica", "Centro trapianti",
"Chirurgia epatobiliare", "Dh oncologico", "Radioterapia", "Chirurgia",
"Chirurgia oncologica", "Gastroenterologia", "Radiologia"), Fascia.oraria = c("00:00 - 3:00",
"00:00 - 3:00", "00:00 - 3:00", "00:00 - 3:00", "00:00 - 3:00",
"00:00 - 3:00", "00:00 - 3:00", "00:00 - 3:00", "00:00 - 3:00",
"3:00 - 13:00", "3:00 - 13:00", "3:00 - 13:00", "3:00 - 13:00",
"3:00 - 13:00", "3:00 - 13:00", "3:00 - 13:00", "3:00 - 13:00",
"3:00 - 13:00", "13:00 - 24:00", "13:00 - 24:00", "13:00 - 24:00",
"13:00 - 24:00", "13:00 - 24:00", "13:00 - 24:00", "13:00 - 24:00",
"13:00 - 24:00", "13:00 - 24:00", "Orario sconosciuto", "Orario sconosciuto",
"Orario sconosciuto", "Orario sconosciuto", "Orario sconosciuto",
"Orario sconosciuto", "Orario sconosciuto", "Orario sconosciuto",
"Orario sconosciuto"), Eventi = c(19.7, 2.19, 0, 0, 0, 0, 0,
0, 0, 4.6, 1.32, 0.66, 0, 0.66, 0, 0, 0.66, 0, 7.77, 0, 1.2,
1.2, 0, 0.6, 0.6, 0, 0.6, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -36L)) %>%
ggplot(aes(str_first_up(Reparto), Eventi)) +
geom_col(aes(fill = Fascia.oraria), position = position_dodge2(preserve = 'total')) +
theme(
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.minor.x = element_line(color = 'gray')
) +
labs(x = NULL, y = 'N. eventi x 100 gg', fill = 'Fascia oraria')
Upvotes: 9
Views: 2985
Reputation: 4929
You can manually set the lines like this:
p +
theme(panel.grid = element_blank()) + # remove grid lines
geom_vline(xintercept = seq(0.5, length(df$Reparto), by = 1), color="gray", size=.5, alpha=.5) # set vertical lines between x groups
where p
is your original plot, and df
is your data.frame.
Obs: To produce this picture, I removed the str_first_up()
from your code since it's not from dplyr
or ggplot
packages (current versions). Also, I added theme_bw()
before your theme settings.
Upvotes: 6