Using ggplot2 and a secondary y-axis, how can I plot a log10 scale on the left y-axis and a linear scale on the right?

huangapple go评论58阅读模式
英文:

Using ggplot2 and a secondary y-axis, how can I plot a log10 scale on the left y-axis and a linear scale on the right?

问题

这让我感到疯狂,主要是因为我以前做过,但找不到相关代码。

假设我有以下数据框:

df <- tibble(
  时间 = 0:19,
  VAL1 = seq(from = 10, to = 2500, length.out = 20),
  VAL2 = seq(from = 1, to = 30, length.out = 20))

我想绘制具有较大范围的VAL1,使用对数刻度在左y轴上绘制,并且绘制具有较小范围的VAL2,使用线性刻度在右y轴上绘制。

我知道有其他示例(请参见这里这里),但似乎无法使用这些方法正确对齐y轴。

有什么想法?

英文:

This is driving me crazy, mostly because I've done it before and can't find the code for it.

Let's say I have the following dataframe:

df &lt;- tibble(
  TIME = 0:19,
  VAL1 = seq(from = 10, to = 2500, length.out = 20),
  VAL2 = seq(from = 1, to = 30, length.out = 20))

I'd like VAL1, which has a large range, to be plotted on the left y-axis using a log scale, and VAL2, which has a much smaller range, to be plotted on the right y-axis using a linear scale.

I know there are other examples out there (see here and here), but I can't seem to get the y-axes to line up correctly using those approaches.

Any thoughts?

答案1

得分: 1

ggplot2的次要坐标轴必须是主要坐标轴的线性变换。因此,我们可以将VAL1转换为其对数,以便将两个系列都映射到线性刻度上。(需要一些标签使主要坐标轴的级别显示为指数。)

在这里,我将VAL2除以12,然后加1,以使其覆盖与VAL1的log10类似的范围。次要坐标轴的标签需要相反操作,先减去1,然后乘以12。

ggplot(df, aes(TIME)) +
  geom_line(aes(y = log10(VAL1), color = "VAL1")) +
  geom_line(aes(y = VAL2/12 + 1, color = "VAL2")) +
  scale_y_continuous(
    labels = function(x) scales::comma(round(10^x), accuracy = 1),
    breaks = c(0:10, 0:10 + 0.3979, 0:10 + 0.69897),
    minor_breaks = NULL,
    sec.axis = sec_axis(~(.-1)*12))

Using ggplot2 and a secondary y-axis, how can I plot a log10 scale on the left y-axis and a linear scale on the right?

英文:

ggplot2's secondary axes have to be a linear transformation of the primary axis. So we can convert VAL1 to its log so that both series can be mapped to a linear scale. (With some labeling to make the primary axis levels show exponentials.)

Here, I divide VAL2 by 12 and add one to make it cover similar range as the log10 of VAL1. The secondary axis labeling needs to the reverse, subtracting 1 and then multiplying by 12.

ggplot(df, aes(TIME)) +
  geom_line(aes(y = log10(VAL1), color = &quot;VAL1&quot;)) +
  geom_line(aes(y = VAL2/12 + 1, color = &quot;VAL2&quot;)) +
  scale_y_continuous(
    labels = function(x) scales::comma(round(10^x), accuracy = 1),
    breaks = c(0:10, 0:10 + 0.3979, 0:10 + 0.69897),
    minor_breaks = NULL,
    sec.axis = sec_axis(~(.-1)*12))

Using ggplot2 and a secondary y-axis, how can I plot a log10 scale on the left y-axis and a linear scale on the right?

huangapple
  • 本文由 发表于 2023年5月11日 10:49:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定