绘制具有2个y轴不同比例的2 xts对象

问题描述 投票:0回答:1

我在同一张图表中绘制两个不同的变量时遇到问题。我想绘制COT余额和USD / BRL的价格变量(数据是一个xts对象)。

tail(COT_USD_BRL)
           Long.Positions Short.Positions Change.Long Change.Short X..Long X..Short
2019-11-12           1662           11742        -564         -956     3.1     21.9
2019-11-19           2619           10955         957         -788     4.6     19.2
2019-11-26           3935            9697        1316        -1258     5.7     14.0
2019-12-03           7351           11066        3416         1369    11.9     17.9
2019-12-10           8339            7046         988        -4020    14.3     12.1
2019-12-17           4681           10964       -3658         3918     8.6     20.2
           COT.Balance  Price
2019-11-12       -18.8 4.1677
2019-11-19       -14.6 4.1945
2019-11-26        -8.3 4.2332
2019-12-03        -6.0 4.2066
2019-12-10         2.2 4.1470
2019-12-17       -11.6 4.0719

比例不同。价格变量不适合第二个刻度,我也不知道为什么。有人可以帮我吗?我使用的代码是:

  ggplot(data = COT_USD_BRL, aes(x = index(COT_USD_BRL), y = COT_USD_BRL$COT.Balance)) +
  geom_line(inherit.aes = TRUE) +
  scale_y_continuous(name = "USD_BRL", sec.axis = sec_axis(~. /(100)+3.2)) +
  geom_line(aes(x = index(COT_USD_BRL), y = COT_USD_BRL$Price), color = "red") +
  scale_x_date(date_breaks = "6 months", date_labels = "%b-%Y") + theme_linedraw()

这是情节:

COT Balance x Price

[请让我知道是否错过了一些有用的信息。

r ggplot2 xts
1个回答
0
投票

这是因为sec.axis仅创建轴标签,而不用作绘制数据的参考轴。因此,第二组数据是基于左y轴绘制的。您需要对第二个y值Price应用比例因子,以便与左y轴和USD_BRL的值匹配。

没有数据集的可复制示例(请参见此处:How to make a great R reproducible example),很难确定正确的比例因子,但也许您应该从此开始:

library(ggplot2)
ggplot(data = COT_USD_BRL, aes(x = index(COT_USD_BRL), y = COT_USD_BRL$COT.Balance)) +
  geom_line(inherit.aes = TRUE) +
  scale_y_continuous(name = "USD_BRL", sec.axis = sec_axis(~. /10, name = "Price") +
  geom_line(aes(x = index(COT_USD_BRL), y = COT_USD_BRL$Price*10), color = "red") +
  scale_x_date(date_breaks = "6 months", date_labels = "%b-%Y") + theme_linedraw()

希望它可以帮助您找到解决问题的方法。

© www.soinside.com 2019 - 2024. All rights reserved.