Legend in rows and columns


I am looking to display the legend of my graph in rows and columns (maximum of 4 x 5). This is because I am attempting to save space on my page by placing the legend in the graph, at the upper-right corner. I am able to switch the orientation for the legend of update_layout when there are 5 or more keys in the legend, but when I switch it from horizontal to vertical , the legend becomes completely vertical and protrudes out of the graph.

Any help would be appreciated.