【问题标题】:Duplicating (and modifying) discrete axis in ggplot2在ggplot2中复制(和修改)离散轴
【发布时间】:2018-01-03 20:08:38
【问题描述】:

我想将 ggplot2 图上的左侧 Y 轴复制到右侧,然后更改离散(分类)轴的刻度标签。

我已经阅读了this question 的答案,但是正如on the package's repo page 所见,switch_axis_position() 函数已从cowplot 包中删除(作者引用(即将发布?)ggplot2 中的本机功能) .

我在 ggplot2 的辅助轴上看到了 reference 页面,但是该文档中的所有示例都使用 scale_y_continuous 而不是 scale_y_discrete。而且,确实,当我尝试使用离散函数时,我得到了错误:

Error in discrete_scale(c("y", "ymin", "ymax", "yend"), "position_d",  : 
unused argument (sec.axis = <environment>)

有没有办法用 ggplot2 做到这一点?即使是完全破解的解决方案对我来说也足够了。提前致谢。 (以下 MRE)

library(ggplot2)

# Working continuous plot with 2 axes
ggplot(mtcars, aes(cyl, mpg))  + 
    geom_point() + 
    scale_y_continuous(sec.axis = sec_axis(~.+10))


# Working discrete plot with 1 axis
ggplot(mtcars, aes(cyl, as.factor(mpg)))  + 
    geom_point() 


# Broken discrete plot with 2 axes
ggplot(mtcars, aes(cyl, as.factor(mpg)))  + 
    geom_point() +
    scale_y_discrete(sec.axis = sec_axis(~.+10))

【问题讨论】:

  • 查看scale_y_discrete 的来源,没有用于指定辅助轴的选项/参数。因此,任何解决方案都可能必须是 hack。
  • 我在 ggplot 提出了一个 issue 来支持 sec.axisscale_y/x_discrete() 中的原生支持。

标签: r ggplot2 tidyverse


【解决方案1】:

取你的离散因子并用数字表示它。然后您可以对其进行镜像并将刻度重新标记为因子级别而不是数字。

library(ggplot2)

irislabs1 <- levels(iris$Species)
irislabs2 <- c("foo", "bar", "buzz")

ggplot(iris, aes(Sepal.Length, as.numeric(Species))) +
  geom_point() +
  scale_y_continuous(breaks = 1:length(irislabs1),
                     labels = irislabs1,
                     sec.axis = sec_axis(~.,
                                         breaks = 1:length(irislabs2),
                                         labels = irislabs2))

然后根据需要在比例尺中调整expand = 参数,以更接近地模仿默认的离散比例尺。

【讨论】:

  • 根据 ggplot 帮助“连续变量的默认值为 c(0.05, 0),离散变量的默认值为 c(0, 0.6)。”对我来说 expand = c(0,0.6) 给出了非常好的结果
  • 刚刚又找到了这个。还是没有更好的办法吗?现在有人知道更简单的方法吗?
  • @TobiO 我已经有几年没有关注 ggplot 的开发了,但你可以随时在他们的 github 存储库上提交一份带有良好 reprex 的错误报告。
  • 我又找到了这个,因为我一直在寻找解决方案,但在完成后的几周内才找到一个功能请求,并提出了与您类似的建议 :-)
  • Github 上实际上有一个未解决的 issue,请在此处发表评论,让团队知道您仍然感兴趣:github.com/tidyverse/ggplot2/issues/3171
猜你喜欢
  • 2017-03-01
  • 2021-11-27
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2019-03-25
相关资源
最近更新 更多