我有一张图表,显示了一周的数据。
问题是它没有显示轴上的所有日期值(代码如下):
如何解决此问题以显示所有7个日期值?
代码:
数据集:
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")
图表代码:
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
答案 0 :(得分:1)
Jack Brookes建议使用scale_x_date(date_breaks = "1 day")
。这不太有效,因为它要求数据为Date
类。不幸的是,这有点模棱两可,因为与时间对应的日期取决于您的时区。如果你碰巧在时区NZ
,那么这可能会给你你想要的东西:
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()
您可以使用OlsonNames()
查看R将识别的时区名称列表。您的系统也可能接受其他人。