0

I am having problems while plotting 2 different variables in the same chart. I want to plot the COT Balance and the Price variables of USD/BRL(data is an xts object).

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

The scales are different. The price variable is not fitting right the second scale and I don't know why. Someone could help me? The code I'm using is:

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

This is the plot:

COT Balance x Price

Please, let me know if I miss some usefull information.

1 Answers1

0

It is because sec.axis only create an axis labeling but it is not use as a referential axis to plot data. So your second set of data is plotting based on the left y-axis. You need to apply a scale factor to your second y value Price in order to match to the left y-axis and values of USD_BRL.

Without a reproducible example of your dataset (see here: How to make a great R reproducible example), it is hard to be sure of the correct scale factor, but maybe you should start with this:

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

Hope it helps you to figure out the solution to your problem.

dc37
  • 15,840
  • 4
  • 15
  • 32