'How can I make time series data with multiple lines?

I want to plot the yield of sugarcane, coconut and rice in time. But I got this output:

![My output plot][1]



Solution 1:[1]

Your data should be aggregated first, since it has multiple entries for the same date and crop, I assume you want sum as aggregation function. In the data argument I use transform to apply ISOdate (see other answer) as well as define a numeric vector for pch and color for plotting.

a <- aggregate(Yield ~ ., 
               transform(data, Year=ISOdate(Year, 1, 1, 0),
                               clr=as.integer(factor(Crop)) + 1), FUN=sum) 

Then, plot and empty base plot, I suggest logarithmic might be suitable with you data. Next, loop lines over the crops using by. Finally place a nice legend that's it.

Here a basic version:

plot(Yield ~ Year, a, log='y', type='n')
by(a, a$Crop, \(x) with(x, lines(Yield ~ Year, type='b', col=clr, pch=clr)))
legend('right', legend=unique(data$Crop), col=unique(a$clr), pch=unique(a$clr))

enter image description here

Solution 2:[2]

ggplot(data, aes(x = Year, y = Yield, colour = Crop, group = Crop)) + geom_smooth() + xlab("")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jay.sf
Solution 2 Emily Rossa