import pandas as pd import plotly.graph_objs as go import plotly.offline as py # 读取csv文件 df = pd.read_csv('Studentslnfo.csv', encoding='gbk') # 统计不同性别下每个家长受教育水平的人数 female_parent_edu_counts = df[df['性别'] == '女']['家长受教育水平'].value_counts() male_parent_edu_counts = df[df['性别'] == '男']['家长受教育水平'].value_counts() # 绘制三维柱状图 trace1 = go.Bar(x=female_parent_edu_counts.index, y=female_parent_edu_counts.values, z=[0] * len(female_parent_edu_counts), name='女性') trace2 = go.Bar(x=male_parent_edu_counts.index, y=male_parent_edu_counts.values, z=[1] * len(male_parent_edu_counts), name='男性') data = [trace1, trace2] layout = go.Layout(title='不同性别下每个家长受教育水平的人数', scene=dict(xaxis=dict(title='家长受教育水平'), yaxis=dict(title='人数'), zaxis=dict(title='性别'))) fig = go.Figure(data=data, layout=layout) py.plot(fig, filename='parent_edu_counts.html') 优化代码使其能在jupyter中显示
时间: 2023-12-17 21:05:56 浏览: 140
好的,以下是优化后的代码,可在Jupyter Notebook中直接显示三维柱状图:
```python
import pandas as pd
import plotly.graph_objs as go
import plotly.offline as pyo
from IPython.display import display, HTML
# 读取csv文件
df = pd.read_csv('Studentslnfo.csv', encoding='gbk')
# 统计不同性别下每个家长受教育水平的人数
female_parent_edu_counts = df[df['性别'] == '女']['家长受教育水平'].value_counts()
male_parent_edu_counts = df[df['性别'] == '男']['家长受教育水平'].value_counts()
# 绘制三维柱状图
trace1 = go.Bar(x=female_parent_edu_counts.index, y=female_parent_edu_counts.values, z=[0] * len(female_parent_edu_counts), name='女性')
trace2 = go.Bar(x=male_parent_edu_counts.index, y=male_parent_edu_counts.values, z=[1] * len(male_parent_edu_counts), name='男性')
data = [trace1, trace2]
layout = go.Layout(title='不同性别下每个家长受教育水平的人数', scene=dict(xaxis=dict(title='家长受教育水平'), yaxis=dict(title='人数'), zaxis=dict(title='性别')))
fig = go.Figure(data=data, layout=layout)
# 显示三维柱状图
pyo.init_notebook_mode(connected=True)
pyo.iplot(fig)
# 显示HTML代码
html = pyo.plot(fig, include_plotlyjs=False, output_type='div')
display(HTML(html))
```
这段代码会在Jupyter Notebook中显示一个交互式的三维柱状图,并在下方显示相应的HTML代码。
阅读全文