Abhishek Choudhary
Abhishek Choudhary

Reputation: 8385

Plot ggplot line graph having 2 seperate columns value in R

I have a dataset as follows-

    mo  Deposit Withdrawl
1   01  430013.5    363620
2   02  399733.5    364426
3   03  782495.0    897652
4   04  349144.7    395913
5   05  470808.5    410153
6   06  568985.0    720753
7   07  676970.2    355392

Now I want to plot a line graph which will show based on each mo (x-axis) , how is Deposit and Withdrawl working , precisely the graph will have mo as X axis and expecting 2 lines as Deposit and Withdrawl showing a line graph connecting to there points with different color in ggplot or qplot.

Tried

ggplot(data=month.dep,
       aes(x=mo, y=y, colour=Deposit)) +
  geom_line()

But above won't work as my objective is different and my colour type is no some binary value

Upvotes: 0

Views: 1516

Answers (1)

eipi10
eipi10

Reputation: 93761

First melt your data into long format then plot it:

library(reshape2)   # For melt function

month.dep.m = melt(month.dep, id.var="mo")

ggplot(month.dep.m, aes(x=mo, y=value, colour=variable)) +
       geom_line()

In general, ggplot2 prefers data in long format. In this case, Deposit and Withdrawal are two categories of currency values. So we use melt to put those two categories into a single column called variable that ggplot uses for the colour aesthetic, while the currency values likewise go into a new value column, each value going with its corresponding category in the variable column.

Upvotes: 3

Related Questions