在同一y轴上绘制两条线; Ggplot,R

时间:2018-09-03 09:35:54

标签: r ggplot2

我有一个ggplot图,我想在上面画两条线(来自不同的列,但日期相同)。我得到的是两条彼此堆叠的线,但是我希望具有正确的y轴(顺序正确),并且线彼此重叠。

这是我要绘制的数据:

final_table:

 Month              a                      b
1 2018-04      758519.397875       2404429.258675
2 2018-05      964792.603725        1995902.14473
3 2018-06      703170.240575        1294997.84319

这是我的代码:

bla3 <- melt(final_table, id='Month')
ggplot(data=bla3, aes(x=Month, y=value, colour= variable, group=variable)) + 
  geom_line() 

我得到的输出(注意y轴是完全错误且无序的。)

gg_plot

1 个答案:

答案 0 :(得分:0)

我猜您的数据变量格式不正确。例如。如果您运行

class(final_table$month) 

这应该产生日期。因此,您需要将其转换为正确的格式。这是您的电话号码示例。

Month <- as.character(c("2018-04", "2018-05", "2018-06")) #or convert it to character after
a <- c(758519.397875, 964792.603725, 703170.240575)
b <- c(2404429.258675, 1995902.14473, 1294997.84319)

final_table <- data.frame(Month, a, b)

 #your Month variable is messed up, you actually need the day!
 final_table$Month <- as.Date(paste(final_table$Month,"-01",sep=""))

library(reshape) #need to load that for melt
bla3 <- melt(final_table, id='Month')
ggplot(data=bla3, aes(x=Month, y=value, colour= variable, group=variable)) +   
geom_line()

There you go!