0

I ploting in log scale

library(ggplot2)
library(scales)
library(tibble)
tibble(
x = seq(1, 10, .01),
y = sin(log(x)*pi) + 2
) %>% 
ggplot(aes(x,y)) + 
geom_line() + 
scale_x_continuous(trans = log_trans()) + 
scale_y_continuous(trans = log_trans())

how can I add to this plot the data from

    tibble(
   x1 = seq(2, 11, .01),
   y1 = sin(log(x1)*pi) + 2
   )
1
  • typo, need to change log(x) to log(x1) Commented Oct 13, 2023 at 15:32

1 Answer 1

3

Two things:

  • you need to un-log transform the y1 data, since ggplot assumes all data needs to be transformed; and
  • you need to map the new variable names

Starting with your original plot unchanged (but assigned to gg):

gg <- tibble(
    x = seq(1, 10, .01),
    y = sin(log(x)*pi) + 2
  ) %>% 
  ggplot(aes(x,y)) + 
  geom_line() + 
  scale_x_continuous(trans = log_trans()) + 
  scale_y_continuous(trans = log_trans())

# fixing log(x) -> log(x1)
newdata <- tibble(
  x1 = seq(2, 11, .01),
  y1 = sin(log(x1)*pi) + 2
)

We can plot with:

gg + 
  geom_line(aes(x = x1),
            data = mutate(newdata, y = exp(y1)), color = "red")

ggplot log axes with added data

FYI, unless you need scale_*_continuous for other reasons, I think scale_*_log10() presents better looking default ticks.

gg <- tibble(
    x = seq(1, 10, .01),
    y = sin(log(x)*pi) + 2
  ) %>% 
  ggplot(aes(x,y)) + 
  geom_line() + 
  scale_x_log10() + 
  scale_y_log10()
gg + 
  geom_line(aes(x = x1), data = mutate(newdata, y = exp(y1)), color = "red")

same image using scale_x_log10


Another alternative (not sure what you're going for) is more generic and completely ancillary to the log-axis issue: we assign data=, but because the original aesthetics x and y are not both present, we need to map them explicitly.

gg +
  geom_line(aes(x = x1, y = y1), data = newdata, color = "red")

another ggplot, this time the red line overlaps

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

8 Comments

thanks, but i think there is a problem in y scale, when we plot newdata alone, they are between 1 and 3. but when plotting it with gg they are now from 3 to above 10. any explainations?
you tell me ... what exactly do you expect this to look like? You have non-log data that you plot in a lot scale, and then you have log-data ... do you expect it to be double-logged?
see my edit @Tpellirn, perhaps that's it?
in fact i am trying to plot like loglog in matlab
That doesn't clear it up for me. I look at mathworks.com/help/matlab/ref/loglog.html and I see two scales, both in "log", with appropriate major/minor gridlines and a curve. That's what I think I'm giving you here. Please explain in words what is wrong with the curves we see here.
|

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.