簡體   English   中英

未在 ggplot 中顯示所有 x 軸標簽

[英]Not showing all x-axis labels in ggplot

我有一個包含許多列的數據集。 最后一列(標簽)顯示每個用戶(行)的集群成員。 如何編輯我的代碼以僅顯示 x 軸的幾個標簽?,因為現在日期重疊並且無法讀取。 我想顯示每五個日期中的第一個、最后一個和一個。 例如,顯示日期1,5,10,15,....,133 ,其中1133是第一個和最后一個日期。 順便說一句,我使用了scale_x_date()但沒有成功。

數據樣本

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")))

代碼

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))

您可以使用scale_x_date 根據@Rui Barradas 的評論,您首先必須將日期的 class 設置為"Date"

然后,使用scale_x_date ,您可以使用date_breaks控制休息時間。 您還可以使用date_labels控制格式。 有關更多信息,請參閱?scale_x_date 以下是如何每 5 天擁有一個軸 label:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM