Reputation: 7530
I have a chart that shows a week's worth of data.
The trouble is that it doesn't show all of the date values on the axis (code is below):
How can I fix this to show all 7 date values?
Code:
Dataset:
us_chats <- structure(list(date = structure(c(1524783600, 1524870000, 1524870000,
1524956400, 1525042800, 1525042800, 1525129200, 1525129200, 1525215600,
1525215600, 1525302000), class = c("POSIXct", "POSIXt"), tzone = ""),
type = c("Completed", "Completed", "Missed", "Completed",
"Completed", "Missed", "Completed", "Missed", "Completed",
"Missed", "Completed"), count = c(2L, 2L, 1L, 1L, 7L, 2L,
2L, 1L, 5L, 4L, 4L)), row.names = c(NA, -11L), class = "data.frame")
Chart code:
us_chats %>%
spread(type, count, fill = 0) %>% # Spread the count column in missed and completed
mutate(Total = Completed + Missed) %>% # Create the Total column
ggplot(aes(date, Total)) +
geom_col(aes(fill = "Total"),
colour = "black") + # total bar (with stat = "identity")
geom_col(aes(y = Missed, fill = "Missed"),
colour = "black") + # missed bar
geom_text(aes(label = paste("Total chats:", Total)), # add total label
hjust = -0.05, vjust = 1) +
geom_text(aes(label = paste("Missed chats:", Missed, "(", round(Missed/Total*100, 2), "%)")), # add missed label and calculate percentage
hjust = -0.05, vjust = -0.5, color = "red") +
scale_fill_manual(name = "", # Manual fill scale
values = c("Total" = "forestgreen", "Missed" = "red")) +
scale_y_continuous(limits = c(0, max(us_chats$count) * 3)) + # Make labels visible
coord_flip() # switch x and y axes
Upvotes: 0
Views: 87
Reputation: 44877
Jack Brookes suggested using scale_x_date(date_breaks = "1 day")
. That doesn't quite work because it requires the data to be of class Date
. Unfortunately, that is a little ambiguous, because the date corresponding to a time depends on your time zone. If you happen to be in timezone NZ
, then this may give you what you want:
us_chats %>%
spread(type, count, fill = 0) %>% # Spread the count column in missed and completed
mutate(Total = Completed + Missed) %>% # Create the Total column
ggplot(aes(as.Date(date, tz = "NZ"), Total)) +
geom_col(aes(fill = "Total"),
colour = "black") + # total bar (with stat = "identity")
geom_col(aes(y = Missed, fill = "Missed"),
colour = "black") + # missed bar
geom_text(aes(label = paste("Total chats:", Total)), # add total label
hjust = -0.05, vjust = 1) +
geom_text(aes(label = paste("Missed chats:", Missed, "(", round(Missed/Total*100, 2), "%)")), # add missed label and calculate percentage
hjust = -0.05, vjust = -0.5, color = "red") +
scale_fill_manual(name = "", # Manual fill scale
values = c("Total" = "forestgreen", "Missed" = "red")) +
scale_y_continuous(limits = c(0, max(us_chats$count) * 3)) + # Make labels visible
scale_x_date(date_breaks = "1 day", name = "Date") +
coord_flip()
You can use OlsonNames()
to see a list of timezone names that R will recognize. Your system may accept some others, too.
Upvotes: 1