I am working with the R programming language.
I have the following data:
# "d"
structure(list(iteration = 1:20, State_1 = c(0.833333333333333,
0.805555555555556, 0.782407407407408, 0.760030864197531, 0.738297325102881,
0.717185356652949, 0.696677097622314, 0.676755282159732, 0.657403140559112,
0.638604382721342, 0.620343184372478, 0.602604173741329, 0.585372418619872,
0.568633413793723, 0.55237306883206, 0.536577696226679, 0.521233999870233,
0.506329063863936, 0.491850341645319, 0.477785645426876), State_2 = c(0.166666666666667,
0.166666666666667, 0.162037037037037, 0.157407407407407, 0.152906378600823,
0.148533950617284, 0.144286551211706, 0.140160608139003, 0.136152648383123,
0.132259298157039, 0.128477280146397, 0.124803410753146, 0.121234597415746,
0.117767836005936, 0.114400208299943, 0.111128879522001, 0.107951095958113,
0.104864182638058, 0.101865541083666, 0.0989526471214974), State_3 = c(0,
0.0277777777777778, 0.0555555555555555, 0.0825617283950617, 0.108796296296296,
0.134280692729767, 0.159036351165981, 0.183084109701265, 0.206444211057766,
0.229136319121619, 0.251179535481126, 0.272592415505525, 0.293392983964383,
0.313598750200341, 0.333226722867997, 0.35229342425132, 0.370814904171654,
0.388806753498006, 0.406284117271016, 0.423261707451627)), row.names = c(NA,
20L), class = "data.frame")
I am trying to plot the data as follows:
library(ggplot2)
p = ggplot() + geom_line(data = d, aes(x = iteration, y = State_1), color = "blue") + geom_line(data = d, aes(x = iteration, y = State_2), color = "red") + geom_line(data = d, aes(x = iteration, y = State_3), color = "green") + xlab('Number of Iterations') + ylab('Probability of Being in a Certain State') + ggtitle("Plot") theme(legend.position="bottom")
For some reason, the legend is not appearing even though I have specified the legend in the ggplot command. On top of that, apparently the legend should automatically be appearing in ggplot2 (https://r-graph-gallery.com/239-custom-layout-legend-ggplot2.html).
Does anyone know how to fix this?
Thanks!
Note: For some reason, the "melt" option seems to automatically fix this:
library(reshape2)
mdf <- reshape2::melt(d, id.var = "iteration")
ggplot(mdf, aes(x = iteration, y = value, colour = variable)) +
geom_point() +
geom_line()