R-scale_x_reordered()函数不允许我更改x轴标签吗?

时间:2019-09-13 17:01:02

标签: r ggplot2

我不知道如何将x轴的标签更改为scale_x_reordered()函数? 代码scale_x_reordered(breaks = surcharge $ arret,标签= surcharge $ arret_fr)不起作用,并显示错误消息。

reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
  new_x <- paste(x, within, sep = sep)
  stats::reorder(new_x, by, FUN = fun)
}

scale_x_reordered <- function(..., sep = "___") {
  reg <- paste0(sep, ".+$")
  ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}

ggplot(data=surcharge, aes(x=reorder_within(arret, sqcearr, dir), y=value)) +
geom_point() +
geom_line() +  
facet_wrap(~dir, scales = "free_x", ncol=1) +
scale_x_reordered(breaks=surcharge$arret, labels=surcharge$arret_fr)
  

discrete_scale(c(“ x”,“ xmin”,“ xmax”,“ xend”),“ position_d”,   :正式参数“标签”与多个实际参数匹配

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果我正确阅读了您的代码,则对scale_x_discrete的呼叫已经

错误消息告诉您,您在该行中两次定义了labels参数

ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)

由于您同时将breakslabels参数传递到...的{​​{1}}中,因此该行变为

scale_x_reordered

因此您要两次定义ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), breaks=surcharge$arret, labels=surcharge$arret_fr)

我将完全放弃labels函数,并在定义ggplot对象的标签上执行想要的操作。

scale_x_reordered

您也可以更改此行

ggplot(data=surcharge, aes(x=reorder_within(arret, sqcearr, dir), y=value ) +
geom_point() +
geom_line() +  
facet_wrap(~dir, scales = "free_x", ncol=1) +
scale_x_discrete(labels = function(x) gsub("___.+$", "", surcharge$arret_fr), 
  breaks=surcharge$arret)

scale_x_reordered(breaks=surcharge$arret, labels=surcharge$arret_fr)

和这一行

scale_x_reordered(x=surcharge$arret_fr,breaks=surcharge$arret)

对此

scale_x_reordered <- function(..., sep = "___") {