Search code examples
pythonpandasplotlypie-chart

How to plot pandas Dataframe as a Pie chart using plotly


i was able to find the count and percentage using pandas. But when I try to plaot, I only see an empty HTML page. Kindly assist in plotting the below dataframe as a pie chart.

Python code

import pandas as pd
import plotly.graph_objects as go
import plotly.offline as py
df = pd.read_excel('data/master.xlsx')

#Commercials ISTQB foundation data
df_commercials=df[(df['Domain']=='Commercials')]
ds=df_commercials['ISTQB Foundation']
count = ds.value_counts()
print(count)
print()
print("=================================================")
percent = ds.value_counts(normalize=True)

istqbF_series = round((percent*100),2).astype(str)+'%'
istqbF_df = pd.DataFrame({'ISTQB Foundation':istqbF_series.index,'percentage':istqbF_series.values})

print(istqbF_df)
print()
labels = istqbF_df['ISTQB Foundation']
values = istqbF_df['percentage']


# trace = go.Pie(labels=labels, values=values)
# fig = go.Figure(data=[go.Pie(labels=labels, values=values)])
#
#
# py.plot(fig, filename='ISTQB_Foundation_pie_chart.html')

Output :

enter image description here

I would like to plot the output in the form of a pie chart,with (ISTQB Foundation vs percentage) , on hover the count to be displayed.

I tried searching the net for days, couldn't end up with a tutorial to guide me on this. Any assistance is much appreciated


Solution

  • here you may be getting error as both your columns are categorical (string). Try as below

    import plotly.offline as py
    from plotly.graph_objs import Pie, Layout,Figure
    
    percent = ds.value_counts(normalize=True).mul(100).round(2)
    
    
    _layout = Layout(title='ISTQB_Foundation')
    _data = Pie(labels=percent.index.tolist(),values=percent.values.tolist(),hoverinfo='label+percent')
    fig = Figure(data=[_data], layout=_layout)
    
    # save html file to local
    py.plot(fig,filename='ISTQB_Foundation_pie_chart.html')