I have a table with some column, let's say: years 1910-1935, number of sold product, and some arithmetic mean in the last col.
I try to plot it in ggplot in R. And I got a proper plot for year~mean. But my problem is: I need to add a line to that plot with years~sold products. They have a completely different value (the first plot have a Y value: 0 - 3.5, second: 0 - 1400). So if I try to add my second line, the first values are flatting.
How can I include the second chart so that the years are based on the X axis (i.e. years from the first chart) and sold products get a new Y2 axis on the right (so that they do not flatten the chart)?
I tried to add new plot to another, but the Y2 didn't fit to first plot area (i had a Y2 axis inside a plot area).
Code:
par(mar=c(5,5,5,5))
ggplot(prod, aes(year, mean)) +
geom_line(colour = "red")
#ggplot(prod, aes(year, numOfProd)) + geom_line()
ggplot(prod, aes(year, mean)) + geom_smooth(method="glm", formula=y~poly(x,3), se=FALSE, colour ="red") +
geom_smooth(method = "lm", formula=y~x, se = FALSE, colour = "blue") +
stat_smooth(method = "lm", colour = "blue") +
#geom_point() +
xlab("year of sold") + ylab("Mean[%]") +
scale_x_continuous(breaks = seq(min(inbred_wszystko$rur), max(prod$year), by = 5)) +
scale_y_continuous(breaks = seq(min(prod$mean), max(prod$mean), by = 0.2))
par(new=TRUE)
## Plot the second plot and put axis scale on right
par(mar=c(5,5,5,5))
plot(prod$year, all_prod$numOfprod, xlab="", ylab="", ylim=c(0,1500),
axes=FALSE, type="l", col="dark green")
mtext("Example",side=4,col="black",line=4)
axis(4, ylim=c(0,1500), col="black",col.axis="black",las=2)
So resume: I need to add a line from the second plot (after the second comment) to first plot. They based on the same X.axis but values on Y are different. And also I need to add Y2 axis for that line on right side of the plot. Can someone help?
EDIT: Sample data:
year mean soldProd
1910 0.5 798
1911 0.6 4234
1912 0.3 25
1913 0.1 2423
1914 0.6 4242
1915 0.3 5
1916 0.1 21
1917 0.11 442
1918 0.5 2353
1919 0.6 23
1920 0.3 42
1921 0.1 34
1922 0.3 235
1923 0.1 2
1924 0.5 5
1925 0.5 23
1926 0.5 235
1927 0.6 23
1928 0.3 4
1929 0.1 234
1930 0.5 2
1931 0.5 5
1932 0.5 2
1933 0.6 6
1934 0.3 4
1935 0.1 36