首页 > 解决方案 > 有没有办法为 ggplot2 中的各种可能输入指定绘图轴上显示的中断数?

问题描述

我创建了一个个性化的 y 轴,它以不规则的间隔为 R Shiny 应用程序中的绘图指定中断和标签。根据我输入的数据,y 轴可能太窄(显示不够,如果有的话,中断)或太宽(显示太多中断并且标签重叠)。我尝试使用该expand功能,但是没有适合所有可能输入的值。有没有办法防止这种情况,并且只是规定无论输入如何,轴上都应该有 3 个中断?我一直无法成功实施n.breaks- 这是正确的方法吗?

我在下面创建了一个小型演示 df 来复制问题,但是,该解决方案应该适用于更广泛的值。

y <- c(1 ,2, 3, 45, 63, 24)
x <- c(2000, 2001, 2002, 2003, 2004, 2005)
df <- cbind(x,y)
df <- data.frame(df)


breaks <- c(1, 10, 40,60,65, 75)
labels <- c("a", "b","c", "d", "e", "f")

ggplot(data = NULL, aes(x,y, group=1)) +
  geom_line() +
  scale_y_continuous(breaks = breaks, labels = labels)

type1 <-  filter(df, as.numeric(x) <= 2002)

ggplot(data = type1, aes(x,y, group=1)) +
  geom_line() +
  scale_y_continuous(breaks = breaks, labels = labels)

type2 <-  filter(df, as.numeric(x) >= 2003)

ggplot(data = type2, aes(x,y, group=1)) +
  geom_line() +
  scale_y_continuous(breaks = breaks, labels = labels, expand = expand_scale(c(0.5,0.4)))

非常感谢。

标签: rggplot2

解决方案


你可以试试标签功能

foo <- function(x) {
 require(tidyverse)
  tibble(breaks, labels) %>% 
    right_join(tibble(breaks=x, n=T)) %>% 
    mutate(new = ifelse(!is.na(labels), labels, breaks)) %>% 
    pull(new)
}
ggplot(data = type1, aes(x,y, group=1)) +
     geom_line() +
     scale_y_continuous(labels = foo)

在此处输入图像描述


推荐阅读