Shachi Kurl, the executive director of the Angus Reid Institute, a nonprofit polling firm, said the results showed that both Mr. Trudeau’s Liberal Party and the Conservatives, which both once drew supporters from across the country, could no longer do so.

The Conservatives and their leader Andrew Scheer, a career politician who is anti-abortion and has made disparaging comments about same-sex marriage, were disproportionately backed by voters in Canada’s western Prairie Provinces. Mr. Trudeau’s Liberals were returned largely by voters from the provinces to the east.

Still, even though the election underscored Canada’s polarizations, Mr. Trudeau eked out a second term and a victory for his liberal agenda on issues like climate change and women’s and minority rights.

His slim win, with the Conservatives taking slightly more of the popular vote, was a vindication after a bruising campaign. He was relentlessly attacked over accusations that he had bullied his former justice minister, an Indigenous woman, and his image was tainted by the publication of old photos of him dressing up as racist caricatures.

But the loss of the majority he won in 2015, a chastening result, shows that he personally, and not just his liberal platform, is divisive, with much of his support emanating from urban areas. His Liberals did not win a majority and he will have to govern with the support of smaller parties.