如何在x轴上绘制两个向量,在ggplot2中绘制另一个y轴

时间:2023-01-12 20:17:46

I am trying to plot two vectors with different values, but equal length on the same graph as follows:

我试着画出两个有不同值的向量,但在相同的图上的长度相等:

a<-23.33:52.33
b<-33.33:62.33
days<-1:30

df<-data.frame(x,y,days) 

      a   b    days
 1    23.33 33.33    1
 2    24.33 34.33    2
 3    25.33 35.33    3
 4    26.33 36.33    4
 5    27.33 37.33    5
 etc..

I am trying to use ggplot2 to plot x and y on the x-axis and the days on the y-axis. However, I can't figure out how to do it. I am able to plot them individually and combine the graphs, but I want just one graph with both a and b vectors (different colors) on x-axis and number of days on y-axis.

我试着用ggplot2在x轴上绘制x和y以及y轴上的天数。然而,我不知道怎么做。我可以把它们单独地画出来并把它们结合起来,但是我想要一个图,在x轴上有a和b向量(不同的颜色)在y轴上有天数。

What I have so far:

到目前为止,我所拥有的:

X<-ggplot(df, aes(x=a,y=days)) + geom_line(color="red")
Y<-ggplot(df, aes(x=b,y=days)) + geom_line(color="blue")

Is there any way to define the x-axis for both a and b vectors? I have also tried using the melt long function, but got stuck afterwards.

有没有办法定义a和b的x轴?我也尝试过使用熔体长函数,但后来被卡住了。

Any help is much appreciated. Thank you

非常感谢您的帮助。谢谢你!

1 个解决方案

#1


1  

I think the best way to do it is via a the approach of melting the data (as you have mentioned). Especially if you are going to add more vectors. This is the code

我认为最好的方法是通过融化数据的方法(如你所提到的)。尤其是如果你要加入更多的向量。这是代码

library(reshape2)
library(ggplot2)

a<-23:52
b<-33:62
days<-1:30

df<-data.frame(x=a,y=b,days)
df_molten=melt(df,id.vars="days")

ggplot(df_molten) + geom_line(aes(x=value,y=days,color=variable))

You can also change the colors manually via scale_color_manual.

您还可以通过scale_color_manual手动更改颜色。

#1


1  

I think the best way to do it is via a the approach of melting the data (as you have mentioned). Especially if you are going to add more vectors. This is the code

我认为最好的方法是通过融化数据的方法(如你所提到的)。尤其是如果你要加入更多的向量。这是代码

library(reshape2)
library(ggplot2)

a<-23:52
b<-33:62
days<-1:30

df<-data.frame(x=a,y=b,days)
df_molten=melt(df,id.vars="days")

ggplot(df_molten) + geom_line(aes(x=value,y=days,color=variable))

You can also change the colors manually via scale_color_manual.

您还可以通过scale_color_manual手动更改颜色。