PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 23, 2022

[FIXED] How to plot pandas Dataframe as a Pie chart using plotly

 April 23, 2022     pandas, pie-chart, plotly, python     No comments   

Issue

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')


Answered By - Shijith
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing