简体   繁体   中英

Not showing all x-axis labels in ggplot

I have a dataset having many columns. The last column ( Labels ) shows the cluster member for each user (row). How can I edit my code to show only a few labels of x-axis?, since right now the dates are overlapping and can not be read. I want to show the first, last and one out of every five dates. For example, showing the dates 1,5,10,15,....,133 , which 1 and 133 are the first and the last dates. BTW, I have used the scale_x_date() but I had no success.

Data Sample

mat <- structure(c(1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 2, 3), 
          .Dim = c(3L, 5L), 
          .Dimnames = list(c("A", "B", "C"), 
                           c("2011-1-6", "2011-1-9", "2011-1-15", "2011-2-19", "Labels")))

Code

library(tidyverse)
    mat %>% 
      as.data.frame() %>%
      mutate(id=1:nrow(mat),
             Labels = as.factor(Labels)) %>%
      pivot_longer(cols=starts_with("2011")) %>%
      filter(value==1) %>%
      ggplot(aes(x=name, y=id, color=Labels)) + 
        geom_point() + 
        theme(axis.text.x = element_text(angle = 90))

You can use scale_x_date . Following @Rui Barradas' comment, you first have to set the class of the dates to "Date" .

Then, with scale_x_date , you can control the breaks with date_breaks . You can also control the format with date_labels . See ?scale_x_date for more info. Here is how to have an axis label every 5 days:

mat %>% 
  as.data.frame() %>%
  mutate(id=1:nrow(mat),
         Labels = as.factor(Labels)) %>%
  pivot_longer(cols=starts_with("2011")) %>%
  mutate(name = as.Date(name)) %>%
  filter(value==1) %>%
  ggplot(aes(x=name, y=id, color=Labels)) + 
  geom_point() + 
  scale_x_date(date_labels = "%Y-%m-%d", date_breaks = "5 days") + 
  theme(axis.text.x = element_text(angle = 90))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM