ggplot2:在右边为一个变量创建第二个y轴

时间:2022-10-19 13:56:39

I have a dataframe with 3 different variables for the same time horizon. The first two variables have the same scaling (stock indice values) and can be illustrated with the y-axis. The third variable is an interest rate and ranges only from 0 to 7%, so that I focused on creating an additional y-axis on the right hand side of the plot to illustrate it. But after now 2 days trying and failing, I look for advice in your community. I first tried to separate my dataset and used to par(new=T) "overwrite" my first plot, but that led to more difficulties than before. I already found cases where people looked for a similar problem, but their questions were to special to replicate with my few skills.

我有一个带有3个不同变量的数据爆炸模型。前两个变量具有相同的缩放(股票indice值),可以用y轴表示。第三个变量是利率,范围仅为0到7%,因此我将重点放在在图的右侧创建一个额外的y轴来说明它。但经过2天的尝试和失败,我在你的社区寻求建议。我首先尝试将我的数据集分离,然后使用par(new=T)“重写”我的第一个情节,但这导致了比以前更多的困难。我已经发现有人在寻找类似的问题,但他们的问题是特别的,以我的少数技能复制。

library(reshape2)
library (scales)
library (ggplot2)

df <- data.frame(Variables, Dates)
df <- melt(df, id.vars="Dates") 

ggplot(df, aes(x=Dates, y=value, fill=variable, colour=variable))+geom_line(stat='identity', size=0.5)+ 
      scale_x_date(breaks = date_breaks("3 months"), labels = date_format("%b-%y"))+
      labs(x="Date", y="MSCI Value" )+
      theme_classic()+
      theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))+
      scale_color_manual(values=c("grey0", "orangered2", "royalblue2"))

Here some data (the first 30 observations) to replicate my plot and to illustrate what I mean.

这里有一些数据(前30次观察)来复制我的图并说明我的意思。

Dates <- structure(c(8766, 8797, 8825, 8856, 8886, 8917, 8947, 8978, 9009, 
9039, 9070, 9100, 9131, 9162, 9190, 9221, 9251, 9282, 9312, 9343, 
9374, 9404, 9435, 9465, 9496, 9527, 9556, 9587, 9617, 9648), class = "Date")


Variables <- structure(c(1405.713, 1498.661, 1479.508, 1415.972, 1459.993, 
1464.001, 1460.193, 1488.212, 1533.288, 1493.268, 1536.017, 1469.67, 
1484.177, 1462.17, 1483.771, 1555.59, 1610.111, 1624.192, 1624.007, 
1705.582, 1667.891, 1716.796, 1690.085, 1749.089, 1800.553, 1833.446, 
1844.949, 1875.988, 1920.44, 1922.445, 3.05, 3.25, 3.34, 3.56, 
4.01, 4.25, 4.26, 4.47, 4.73, 4.76, 5.29, 5.45, 5.53, 5.92, 5.98, 
6.05, 6.01, 6, 5.85, 5.74, 5.8, 5.76, 5.8, 5.6, 5.56, 5.22, 5.31, 
5.22, 5.24, 5.27, 1226.99191666667, 1240.457375, 1253.96166666667, 
1267.07825, 1281.38133333333, 1293.99208333333, 1308.05641666667, 
1323.16016666667, 1338.992625, 1353.58925, 1371.2485, 1385.3055, 
1399.57704166667, 1412.76375, 1425.710875, 1438.80775, 1451.77004166667, 
1464.062625, 1476.80325, 1491.8025, 1502.652, 1516.61345833333, 
1527.86608333333, 1544.914875, 1561.36654166667, 1575.31591666667, 
1590.542625, 1609.70995833333, 1628.89525, 1647.99708333333), .Dim = c(30L, 
3L), .Dimnames = list(NULL, c("MSCI.WORLD", "Funds.Target.Rate", 
"Mean.Rolling")))

The variable "Funds.Target.Rate" should be presented in a more convenient way. Is it possible to create a second y-axis on the right side of the plot that refers to the interest rates of this variable? Thank you for your time and help.

Funds.Target变量”。“速率”应该以更方便的方式呈现。是否有可能在图的右侧创建第二个y轴来表示这个变量的利率?谢谢您的时间和帮助。

1 个解决方案

#1


2  

As far as I know, this is not possible in ggplot2, for good reasons. see this discussion. The only thing possible is to add a second axis which is a re-calculation of the first axis, e.g. Celsius -> Fahrenheit or local differences:

就我所知,这在ggplot2中是不可能的,有充分的理由。看到这个讨论。唯一可能的办法是增加第二个轴,即重新计算第一个轴,例如摄氏-华氏度或局部差异:

ggplot(mpg, aes(displ, hwy)) + 
  geom_point() + 
  scale_y_continuous(
    "mpg (US)", 
    sec.axis = sec_axis(~ . * 1.20, name = "mpg (UK)")
  )

Having said that, you can use that hack for your purposes. First scale the interest rate, so that all variables have the same dimension (1000 - 2000 in your case) - I multiply Interest.Rate by 400. Then add the second axis and make sure the annotations show the unscaled (i.e. divided) values (* 300 and / 300 in your case):

话虽如此,你还是可以利用这个技巧来达到你的目的。第一个是利率,所以所有的变量都有相同的维度(在你的例子中是1000 - 2000)-我乘以利息。率到400年。然后添加第二个轴,确保标注显示未缩放(即分割)的值(* 300和/ 300):

Variables[, 2] <- Variables[, 2] * 300
df <- data.frame(Variables, Dates)
df <- melt(df, id.vars="Dates") 

ggplot(df, aes(x=Dates, y=value, fill=variable, colour=variable))+geom_line(stat='identity', size=0.5)+ 
    scale_x_date(breaks = date_breaks("3 months"), labels = date_format("%b-%y"))+
    labs(x="Date", y="MSCI Value" )+
    theme_classic()+
    theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))+
    scale_color_manual(values=c("grey0", "orangered2", "royalblue2")) + 

    # NEW CODE:
    scale_y_continuous("MSCI Value", sec.axis = sec_axis(~ . /300, name = "Interest Rate")
)

ggplot2:在右边为一个变量创建第二个y轴

#1


2  

As far as I know, this is not possible in ggplot2, for good reasons. see this discussion. The only thing possible is to add a second axis which is a re-calculation of the first axis, e.g. Celsius -> Fahrenheit or local differences:

就我所知,这在ggplot2中是不可能的,有充分的理由。看到这个讨论。唯一可能的办法是增加第二个轴,即重新计算第一个轴,例如摄氏-华氏度或局部差异:

ggplot(mpg, aes(displ, hwy)) + 
  geom_point() + 
  scale_y_continuous(
    "mpg (US)", 
    sec.axis = sec_axis(~ . * 1.20, name = "mpg (UK)")
  )

Having said that, you can use that hack for your purposes. First scale the interest rate, so that all variables have the same dimension (1000 - 2000 in your case) - I multiply Interest.Rate by 400. Then add the second axis and make sure the annotations show the unscaled (i.e. divided) values (* 300 and / 300 in your case):

话虽如此,你还是可以利用这个技巧来达到你的目的。第一个是利率,所以所有的变量都有相同的维度(在你的例子中是1000 - 2000)-我乘以利息。率到400年。然后添加第二个轴,确保标注显示未缩放(即分割)的值(* 300和/ 300):

Variables[, 2] <- Variables[, 2] * 300
df <- data.frame(Variables, Dates)
df <- melt(df, id.vars="Dates") 

ggplot(df, aes(x=Dates, y=value, fill=variable, colour=variable))+geom_line(stat='identity', size=0.5)+ 
    scale_x_date(breaks = date_breaks("3 months"), labels = date_format("%b-%y"))+
    labs(x="Date", y="MSCI Value" )+
    theme_classic()+
    theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5))+
    scale_color_manual(values=c("grey0", "orangered2", "royalblue2")) + 

    # NEW CODE:
    scale_y_continuous("MSCI Value", sec.axis = sec_axis(~ . /300, name = "Interest Rate")
)

ggplot2:在右边为一个变量创建第二个y轴