Search code examples
pythonplotlybar-chartimage-size

Plotly generated pie chart text exceed page boundary


I am using plotly to generate a pie chart, with textinfo set in outside of the sector. However, when number of sectors increase to a large amount, the textinfo will not shown in the figure frame

A MWE is as the following

import plotly.express as px
from random import randint
import pandas as pd

allData = []

for i in range(100):
    ele = {}
    ele['Category'] = "Category_" + str(i)
    ele['number'] = i + 1
    allData.append(ele)

df = pd.DataFrame(allData)

fig = px.pie(names = df['Category'], values = df['number'], hole = 0.5)
fig.update_traces(textinfo = 'label+value', textposition = "outside")
fig.show()

It gives me something like this. Some of the text info get lost in upper and lower boundary Some Text Info Get Lost on upper and lower

When I zoom out the page, all the text info shows up

Zoom out to show all contetents

But this time the font size become quite small to recognize.

Is there a way to generate a large 100% size image with scrollbars? With that all information will be visible.


Solution

  • There are three things you can do :

    • With textinfo='label+value', each label/value pair occupy two lines, you can save some space by showing them on the same line by specifying texttemplate instead.

    • By default the resolution of the plot fits the browser window, you can increase it as necessary by specifying a large layout width/height.

    • The font size is set according to the space available but you can still tweak it (and the font family as well, since some are more readable than others when the size is small, cf. this post).

    fig = px.pie(names=df['Category'], values=df['number'], hole=0.5)
    
    fig.update_traces(texttemplate='%{label}: %{value}', textposition="outside")
    
    fig.update_layout(
        width=2048,
        height=2048,
        font_family='Segoe UI',
        font_size=11
    )
    
    fig.show()