增加y轴上的间距标记ggplot2

时间:2017-04-26 02:06:32

标签: r ggplot2 axis-labels spacing

我想增加y轴刻度的间距,以使图形(标签)更具可读性。我怎样才能做到这一点?

packages_list <- c("dplyr", "data.table", "ggplot2", "mondate", "tidyr", 
"lubridate", "stringr", "ggrepel")
lapply(packages_list, require, character.only = TRUE)

company <- paste(1:61, rep(LETTERS), sep = "")
mort_table <- rep_len(c(6065, 7680, 8590, 9500), length.out = 61)
disc_rate <-  rep_len(c(3,4), length.out = 61)

data <- data_frame(company = company, disc_rate = disc_rate, mort_table = 
mort_table)
ggplot(data, aes(x = company, y= disc_rate, label = disc_rate)) + 
  geom_point(aes(color = factor(mort_table)), size = 6, show.legend = T) + 
  geom_text(color = "white", size = 1.5) +
  geom_hline(yintercept=3.5, size=1, linetype="dotted", color="red") +
  theme(panel.grid.major.x = element_line(), legend.position = "top") + 
  coord_flip()

enter image description here

1 个答案:

答案 0 :(得分:0)

这是我能想到的最好的了。这将刻度标签的数量减少到 5 个。

library(ggplot2)
library(dplyr, warn.conflicts = FALSE)
library(forcats)

company <- paste(1:61, rep(LETTERS), sep = "")
mort_table <- rep_len(c(6065, 7680, 8590, 9500), length.out = 61)
disc_rate <-  rep_len(c(3,4), length.out = 61)

data <- tibble(company, disc_rate, mort_table) 

axis_levels <- 
    data %>%
    mutate(company = fct_inorder(company)) %>%
    pull(company) %>%
    .[seq(1, nlevels(.), length = 5)] %>%
    as.character()

data %>%
    mutate(company = fct_inorder(company)) %>%
    ggplot(aes(x = company, y = disc_rate, label = disc_rate)) + 
    geom_point(aes(color = factor(mort_table)), size = 6, show.legend = TRUE) + 
    geom_text(color = "white", size = 1.5) +
    geom_hline(yintercept = 3.5, size = 1, linetype = "dotted", color = "red") +
    theme(panel.grid.major.x = element_line(), legend.position = "top") + 
    scale_x_discrete(breaks = axis_levels) +
    coord_flip()

reprex package (v1.0.0) 于 2021 年 3 月 25 日创建