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

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

我有一个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

r ggplot2
1个回答
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!

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