R 在不覆盖参数的情况下组合两个比例
关于如何在ggplot2中组合两个R 在不覆盖参数的情况下组合两个比例,r,ggplot2,R,Ggplot2,关于如何在ggplot2中组合两个scale类型调用,有很多问题。然而,其中大多数都涉及以下内容: ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + scale_x_log10() + scale_x_continuous("some new label") #> Scale for 'x' is already present. Adding another scale for 'x
scale
类型调用,有很多问题。然而,其中大多数都涉及以下内容:
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() +
scale_x_log10() +
scale_x_continuous("some new label")
#> Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
这里的解决方案非常简单,只需使用scale\u x_continuous
中的trans
参数即可
我的情况是,我有许多ggplot2辅助函数用于快速绘制。这些函数在函数内部调用scale\ux
,因此不能如此轻松地对其进行编辑。例如:
#helper function
table2 = function(x, prop = F, include_NA = T, sort_descending = T) {
#NA param
if (include_NA) {
NA_param = "always"
} else {
NA_param = "no"
}
#get regular table
tbl = table(x, useNA = NA_param)
#as data frame
d = tibble::data_frame("Group" = names(tbl),
"Count" = as.numeric(tbl)
)
#percent/prob
if (!prop) d$Percent = d$Count / sum(d$Count) * 100 else d$Proportion = d$Count / sum(d$Count)
#sort?
if (!is.null(sort_descending)) {
if (sort_descending) {
d %<>% dplyr::arrange(-Count)
} else {
d %<>% dplyr::arrange(Count)
}
}
d
}
GG_boxplot = function(df, y, x) {
#determine sample sizes
sample_n = df[c(x, y)] %>%
na.omit() %>%
{table2(.[[x]], include_NA = F, sort_descending = NULL)}
#plot
ggplot(df, aes_string(x = x, y = y)) +
geom_boxplot() +
scale_x_discrete(labels = function(x) {str_c(x, "\nn = ", sample_n$Count)})
}
因此,这是一种很好的方法,可以轻松地将类级样本大小添加到标签中。但是,如果我们想用轴更改其他内容,这些标签将被覆盖,除非在特殊情况下,我们可以使用例如xlab
GG_boxplot(iris, "Sepal.Length", "Species") + xlab("no problem")
但如果你想做一些更奇特的事情,问题就出现了:
#> GG_boxplot(iris, "Sepal.Length", "Species") + scale_x_discrete(position = "top")
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
有没有一种好方法可以解决这些类型的覆盖问题
我尝试了两种方法试图告诉ggplot2不要覆盖以前的设置,但没有成功:
> GG_boxplot(iris, "Sepal.Length", "Species") + scale_x_discrete(position = "top", labels = NULL)
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
> GG_boxplot(iris, "Sepal.Length", "Species") + scale_x_discrete(position = "top", labels = waiver())
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
刻薄的回答
如果保存从函数返回的绘图,则可以访问现有的比例标签,并重新设置所需的比例部分
p <- GG_boxplot(iris, "Sepal.Length", "Species")
p + scale_x_discrete(position = 'top',
labels = ggplot_build(p)$layout$panel_scales$x[[1]]$labels)
psample\n
行中的table2
是什么?我也可能很笨,但是你是如何让x+“\nn”+sample\n$count
连接一个字符串而不是paste
?对不起,我忘了提供一些自定义函数的定义table2
只是table
和prop.table
的单变量替换。我重载了+
以用作字符串连接和加法(请参阅)。我认为这样做是可能的。我确实环顾了四周,但没有尝试ggplot\u build
方法。尽管如此,这些便利功能的全部要点,即节省时间/编码。是的,它相当丑陋。但我想如果你经常这样做,你可以做获取xu标签,我想可能有某种聪明的中缀操作符(例如%+add%
)可以避免在复制ggplot2比例、图层等时覆盖设置。
p <- GG_boxplot(iris, "Sepal.Length", "Species")
p + scale_x_discrete(position = 'top',
labels = ggplot_build(p)$layout$panel_scales$x[[1]]$labels)