The first railway in Latvia opened on 25th December, 1861, between Riga and Dinaburga (Daugavpils). At that time, Latvia was part of the Russian Empire, so the line was built to the Russian gauge of 1524mm (now 1520mm) in anticipation of its eventual connection with the rest of the Russian network.
During both the First and Second World Wars, Latvia came under German occupation. Between the wars, it was an independent state but, after the Second World War, Latvia again came within the Russian sphere of influence. It only regained its independence on the breakup of the Soviet Union.
The gauge history of some of the lines is therefore complex. Lines in the northern part of the country have always retained their Russian gauge but, in the south, the Germans regauged many lines to standard gauge during the First World War. These lines were turned back to Russian gauge after the war, only to be put back to standard gauge (along with some other lines) during the Second World War. Finally, under Soviet influence, all the main lines were converted to Russian gauge, which they retain today.
Flag image from CIA World Factbook