Plotly代码报错:AttributeError: module 'plotly.graph_objs' has no attribute 'pie'
Fixing AttributeError: module 'plotly.graph_objs' has no attribute 'pie'
Let's work through this error and get your pie chart up and running smoothly:
Why This Error Occurs
The main issue here is a simple typo combined with Plotly's strict naming conventions:
- Plotly's pie chart object is
go.Pie(capitalized "P"), notgo.pie(lowercase). Plotly uses camelCase for all its graph object classes, so lowercase names won't be recognized. - If you're using a newer Plotly version (v4+), the library is more strict about these naming rules, making typos like this throw explicit attribute errors.
Corrected Code
Here's the fixed version of your code, with additional tweaks for common Plotly pitfalls:
import numpy as np import pandas as pd import plotly.graph_objs as go # Calculate approval status counts temp = train_data['project_is_approved'].value_counts() labels = temp.index sizes = (temp/temp.sum())*100 # Use go.Pie (capital P) instead of go.pie trace = go.Pie(labels=labels, values=sizes, hoverinfo='label+percent') layout = go.Layout(title='Project Proposal Approval Status') data = [trace] # Fix go.figure to go.Figure (capital F) - Plotly's constructor is capitalized fig = go.Figure(data=data, layout=layout) # For modern Plotly versions, use fig.show() to display plots (works in notebooks & scripts) fig.show() # If you're using an older Plotly version that requires py.iplot(), uncomment below: # import plotly.plotly as py # py.iplot(fig)
Key Fixes Breakdown
go.pie→go.Pie: This directly resolves the AttributeError by using the correct capitalized class name.go.figure→go.Figure: Plotly's figure constructor is a capitalized class, so lowercase will cause another error if left uncorrected.py.iplot(fig)→fig.show(): Newer Plotly versions usefig.show()as the standard way to render plots, which works across Jupyter notebooks and standalone Python scripts. If you're stuck on an older version, you can revert topy.iplot()but need to importplotly.plotly as pyfirst.
内容的提问来源于stack exchange,提问作者vishnu
相关产品推荐
相关产品推荐

