0

I am using R.

Suppose I have the following data:

#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)

I can now make plot the above data like this:

library(ggplot2)
library(ggridges)

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

enter image description here

Is it possible to change the x-axis of the above plot so that it uses the scale from the "var" variable?

This would look something like this:

enter image description here

The "ihs" (inverse hyperbolic sine) value corresponds to "var" through the following relationship:

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

For example:

> ihs(70)
[1] 4.941693

> hs( 4.941693)
[1] 69.99997

Can someone please show me how to do this?

Thanks!

References:

1 Answer 1

2

You can achieve this by setting custom labels with 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))))

enter image description here

Note: use function(x) instead of \(x) if you use a version of R <4.1.0

Sign up to request clarification or add additional context in comments.

2 Comments

@ Dion: Thank you for your answer! Just a question: is there a way to do this automatically, without specifying "c(-5, 0, 5, 10)"? Can it just be done using the "r()" function you defined, without specifying "c(-5, 0, 5, 10)"? Thank you so much!
You mean create the vector outside scale_x_continuous()? You could make a vector my_labels and provide that to the labels argument of scale_x_continuous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.