简体   繁体   English

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

[英]Plot two lines on the same y-axis; Ggplot, R

I have a ggplot graph and I want to draw two lines on it (from different columns, but for the same date). 我有一个ggplot图,我想在上面画两条线(来自不同的列,但日期相同)。 What I get are two lines that are stacked on each other, but I want to have the same y-axis, ordered correctly, with the lines overlapping each other. 我得到的是两条彼此堆叠的线,但是我希望具有正确排列的y轴,并且这些线彼此重叠。

This is the data I'm trying to plot: 这是我要绘制的数据:

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

This is my code: 这是我的代码:

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

And the output I get (notice the y-axis is totally wrong and unordered). 我得到的输出(注意y轴是完全错误且无序的)。

gg_plot

I guess that your data variable is not in the right format. 我猜您的数据变量格式不正确。 Eg if you run 例如,如果您跑步

class(final_table$month) 

This should yield date. 这应该产生日期。 So you need to get it into the right format. 因此,您需要将其转换为正确的格式。 Here's an example with your numbers. 这是您的电话号码示例。

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

你去!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM