在trans_new scales包中使用反参数

问题描述

我一直试图在scales包中使用trans_new函数,但是我无法正确显示标签

# percent to fold change
fun1 <- function(x) (x/100) + 1

# fold change to percent
inv_fun1 <- function(x) (x - 1) * 100



percent_to_fold_change_trans <- trans_new(name = "transform",transform = fun1,inverse = inv_fun1)


plot_data <- data.frame(x = 1:10,y = inv_fun1(1:10))


# Plot raw data

p1 <- ggplot(plot_data,aes(x = x,y = y)) +
  geom_point()

# This doesn't really change the plot
p2 <- ggplot(plot_data,y = y)) +
  geom_point() +
  coord_trans(y = percent_to_fold_change_trans)

p1和p2是相同的,而我期望p2是对角线,因为我们正在反转反相函数。如果我用另一个函数(如fun(x)x)替换trans_new中的反参数,则可以看到正确的变换,但标签完全不可用。关于如何定义反参数以获取正确标签位置的任何想法?

解决方法

您不会期望像Private Sub Workbook_Open() 'Step 1: Use the RefreshAll method Workbooks(ThisWorkbook.Name).RefreshAll End Sub 这样的线性函数会改变y轴的外观。请记住,您不是在变换数据,而是在变换y轴。这意味着您正在有效地更改水平网格线的位置,而不是它们所代表的

任何产生线性变换的函数都将导致水平网格线之间的间距固定,这就是您已经拥有的间距。因此情节不会改变。

让我们举一个简单的例子:

fun1

enter image description here

现在让我们创建一个简单的非线性转换:

plot_data <- data.frame(x = 1:10,y = 1:10)

p <- ggplot(plot_data,aes(x = x,y = y)) +
  geom_point() +
  scale_y_continuous(breaks = 1:10)

p

enter image description here

请注意,y轴上的相同,但是因为我们应用了非线性变换,所以网格线之间的距离现在有所变化。

事实上,如果我们绘制数据的变换版本,我们将得到相同的形状:

little_trans <- trans_new(name      = "transform",transform = function(x) x^2,inverse   = function(x) sqrt(x))

p +  coord_trans(y = little_trans)

enter image description here

从某种意义上说,这就是变换所做的全部,只是它将逆变换应用于轴标签。我们可以在此处手动进行操作:

ggplot(plot_data,y = y^2)) +
  geom_point() +
  scale_y_continuous(breaks = (1:10)^2)

enter image description here

现在,假设我改为对x执行更复杂但 linear 的功能:

ggplot(plot_data,y = y^2)) +
  geom_point() +
  scale_y_continuous(breaks = (1:10)^2,labels = sqrt((1:10)^2))

enter image description here

与以前一样。我们可以看到为什么如果再次再次直接应用转换:

little_trans <- trans_new(name      = "transform",transform = function(x) (0.1 * x + 20) / 3,inverse   = function(x) (x * 3 - 20) / 0.1)

ggplot(plot_data,y = y)) +
  geom_point() +
  coord_trans(y = little_trans)

enter image description here

很明显,如果我们对轴标签进行逆变换,我们将得到1:10,这意味着我们将获得原始图。

对于任何线性变换,这同样适用,因此,您获得的结果正是预期的结果。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...