Meesha
Meesha

Reputation: 821

ggplot with two Y axes

dataframe:-  df

  Period        v1      v2
1   2002        1       1
2   2003        5       12
3   2004        9       28
4   2005        16      66
5   2006        23      115

Code:-

ggplot() + geom_line(data=df, aes(x=Period, y=v1, group=1, color="v1")) + 
geom_line(data=df, aes(x=Period, y=v2, group=1, color="v2"))+ theme(legend.title=element_blank()) + scale_y_continuous(name="Count") +
geom_point(data=df, aes(x=Period, y=v1, group=1)) + geom_point(data=df, aes(x=Period, y=v2, group=1))

I am plotting two line graph along with points.The issue I am experiencing is that the values increase in different magnitude and so one of the line graphs "v1" gets condensed at the lower end of the scale and thus harder to read. can anyone please advice in solving this? Also can this code be shortened?

Upvotes: 3

Views: 1516

Answers (1)

Stibu
Stibu

Reputation: 15897

The idea with ggplot2 is that you convert your data into so-called long format, where each observation occupies one line:

library(tidyr)
plot_data <- gather(df, key, value, -Period)
head(plot_data)
##   Period key value
## 1   2002  v1     1
## 2   2003  v1     5
## 3   2004  v1     9
## 4   2005  v1    16
## 5   2006  v1    23
## 6   2002  v2     1

Now, you can map the variable value to y and key to colour to get the same plot easier:

ggplot() + geom_line(data=plot_data, aes(x=Period, y=value, colour = key)) + 
  theme(legend.title=element_blank()) + 
  geom_point(data=plot_data, aes(x=Period, y=value)) +
  scale_y_continuous(name="Count")

I'm not sure what exactly you mean by the data getting harder to read. Maybe, you want a logarithmic y-axis?

ggplot() + geom_line(data=plot_data, aes(x=Period, y=value, colour = key)) + 
  theme(legend.title=element_blank()) +
  geom_point(data=plot_data, aes(x=Period, y=value)) +
  scale_y_log10(name="Count")

enter image description here

Upvotes: 3

Related Questions