0
votes

I have a ggplot graph and I want to draw two lines on it (from different columns, but for the same date). 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.

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

gg_plot

1
Looks like your y variable is being treated as a factor. Try converting it to numeric before plotting?Z.Lin

1 Answers

0
votes

I guess that your data variable is not in the right format. E.g. 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()

There you go!