【问题标题】:divide the y axis to make part with a score <25 occupies the majority in ggplot将 y 轴划分为分数 <25 的部分在 ggplot 中占多数
【发布时间】:2020-12-02 15:05:01
【问题描述】:

我想将 y 轴划分为附图以参与,分数 scale_y_discrete(limits 。我使用了这个p&lt;- p+scale_y_continuous(breaks = 1:20, labels = c(1:20,"//",40:100)),但它还不起作用。

我使用了attached data,这是我的代码

代码

p<-ggscatter(data, x = "Year" , y = "Score" ,
             color = "grey", shape = 21, size = 3, # Points color, shape and size
             add.params = list(color = "blue", fill = "lightgray"), # Customize reg. line
             add = "loess", #reg.line
             conf.int = T, 
             cor.coef = F, cor.method = "pearson",
            xlab = "Year" , ylab= "Score")
p<-p+ coord_cartesian(xlim = c(1980, 2020));p

【问题讨论】:

  • ggplot2 不支持轴中断(出于我同意的原因),但是您是否考虑过对 y 轴进行对数或 sqrt 转换?
  • @teunbrand 感谢您的意见。那么有没有办法在另一个包中产生相同的情节呢?我的高级同事不同意转型。坦克很多

标签: r ggplot2 yaxis


【解决方案1】:

这是我可以得到的假轴中断并调整绘图上部区域的距离。我仍然认为这是一个坏主意,如果这是我的情节,我更喜欢更直接的轴变换。

首先,我们需要一个函数来生成一个转换,将所有值压缩到某个阈值以上:

library(ggplot2)
library(scales)

# Define new transform
my_transform <- function(threshold = 25, squeeze_factor = 10) {
  force(threshold)
  force(squeeze_factor)
  my_transform <- trans_new(
    name = "trans_squeeze",
    transform = function(x) {
      ifelse(x > threshold, 
             ((x - threshold) * (1 / squeeze_factor)) + threshold, 
             x) 
    },
    inverse = function(x) {
      ifelse(x > threshold, 
             ((x - threshold) * squeeze_factor) + threshold, 
             x)
    }
  )
  return(my_transform)
}

接下来,我们将该变换应用于 y 轴并添加一个假轴中断。我使用了香草 ggplot2 代码,因为我发现 ggscatter() 方法令人困惑。

ggplot(data, aes(Year, Score)) +
  geom_point(color = "grey", shape = 21, size = 3) +
  geom_smooth(method = "loess", fill = "lightgray") +
  # Add fake axis lines
  annotate("segment", x = -Inf, xend = -Inf,
           y = c(-Inf, Inf), yend = c(24.5, 25.5)) +
  # Apply transform to y-axis
  scale_y_continuous(trans = my_transform(25, 10),
                     breaks = seq(0, 80, by = 10)) +
  scale_x_continuous(limits = c(1980, 2020), oob = oob_keep) +
  theme_classic() +
  # Turn real y-axis line off
  theme(axis.line.y = element_blank())

您可能会发现在不连续轴上阅读 Hadley Wickham's view 会提供丰富的信息。人们有时 mock 奇怪的 y 轴。

【讨论】:

  • 非常感谢。这样可行。感谢您的努力和时间。赞成。
猜你喜欢
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 2021-06-25
  • 2021-08-03
  • 1970-01-01
相关资源
最近更新 更多