【问题标题】:Creating an Axis for a Plot in terms of another Variable根据另一个变量为绘图创建轴
【发布时间】:2022-01-13 17:48:46
【问题描述】:

我正在使用 R。

假设我有以下数据:

#first data set

v2 <- c("A", "B", "C", "D", "E")
types <- as.factor(sample(v2,1000, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))
var <- rnorm(1000, 10, 10)

first = data.frame(v2, types, var)

#second data set 

v2 <- c("A", "B", "C", "D", "E")
types <- as.factor(sample(v2,50, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))
var <- rnorm(50, 10000, 10)

second = data.frame(v2, types, var)

#final data 

final = rbind(first, second)

#create transformed column

ihs <- function(x) {
    y <- log(x + sqrt(x ^ 2 + 1))
    return(y)
}

final$ihs = ihs(final$var)

我现在可以像这样绘制上述数据:

library(ggplot2)
library(ggridges)

ggplot(final, aes(x = ihs, y = types, fill = types)) +
  geom_density_ridges() + ggtitle("my plot")

是否可以更改上图的 x 轴,使其使用“var”变量中的比例?

这看起来像这样:

“ihs”(反双曲正弦)值通过以下关系与“var”对应:

hs <- function(x) {
    y <- 0.5*exp(-x)*(exp(2*x)-1)
    return(y)
}

例如:

> ihs(70)
[1] 4.941693

> hs( 4.941693)
[1] 69.99997

谁能告诉我怎么做?

谢谢!

参考资料:

【问题讨论】:

    标签: r ggplot2 data-visualization axis axis-labels


    【解决方案1】:

    您可以通过使用scale_x_continuous() 设置自定义标签来实现此目的。

    library(ggplot2)
    # install.packages('ggridges')
    library(ggridges)
    
    hs <- function(x) {
      y <- 0.5*exp(-x)*(exp(2*x)-1)
      return(y)
    }
    
    r <- \(x) round(x, 0)
    
    ggplot(final, aes(x = ihs, y = types, fill = types)) +
      geom_density_ridges() + ggtitle("my plot") +
      scale_x_continuous(labels = r(hs(c(-5, 0, 5, 10))))
    

    注意:如果您使用的是 R 版本,请使用 function(x) 而不是 \(x)

    【讨论】:

    • @Dion:谢谢你的回答!只是一个问题:有没有一种方法可以自动执行此操作,而无需指定“c(-5, 0, 5, 10)”?可以只使用您定义的“r()”函数来完成,而不指定“c(-5, 0, 5, 10)”吗?非常感谢!
    • 你的意思是在scale_x_continuous()之外创建向量?您可以创建一个向量 my_labels 并将其提供给 scale_x_continuouslabels 参数。
    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多