[英]Duplicating (and modifying) discrete axis in ggplot2
I want to duplicate the left-side Y-axis on a ggplot2 plot onto the right side, and then change the tick labels for a discrete (categorical) axis.我想将 ggplot2 图上的左侧 Y 轴复制到右侧,然后更改离散(分类)轴的刻度标签。
I've read the answer to this question , however as can be seen on the package's repo page , the switch_axis_position()
function has been removed from the cowplot
package (the author cited (forthcoming?) native functionality in ggplot2).我已经阅读了这个问题的答案,但是从包的回购页面可以看出,
switch_axis_position()
函数已从cowplot
包中删除(作者引用(即将发布?)ggplot2 中的本机功能)。
I've seen the reference page on secondary axes in ggplot2, however all the examples in that document use scale_y_continuous
rather than scale_y_discrete
.我在 ggplot2 的次轴上看到了参考页,但是该文档中的所有示例都使用
scale_y_continuous
而不是scale_y_discrete
。 And, indeed, when I try to use the discrete function, I get the error:而且,事实上,当我尝试使用离散函数时,我得到了错误:
Error in discrete_scale(c("y", "ymin", "ymax", "yend"), "position_d", :
unused argument (sec.axis = <environment>)
Is there anyway to do this with ggplot2?反正有没有用ggplot2做这个? Even a completely hacked solution will suffice for me.
即使是完全破解的解决方案对我来说也足够了。 Thanks in advance.
提前致谢。 (MREs below)
(下面的 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))
Take your discrete factor and represent it numerically.取你的离散因子并用数字表示。 Then you can mirror it and relabel the ticks to be the factor levels instead of numbers.
然后你可以镜像它并将刻度重新标记为因子水平而不是数字。
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))
Then fiddle with the expand =
argument in the scale as needed to more closely imitate the default discrete scale.然后根据需要摆弄比例尺中的
expand =
参数,以更接近地模仿默认的离散比例尺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.