Plotly Express添加OLS趋势线时出现ImportError且无法显示趋势线的问题求助
Plotly Express添加OLS趋势线时出现ImportError且无法显示趋势线的问题求助
我最近在用Plotly Express绘制散点图并添加OLS趋势线时碰到了棘手的问题:只要在代码里加上trendline='ols'参数,程序就会抛出一大段ImportError错误,趋势线完全无法显示;但如果把趋势线相关的代码去掉,散点图就能正常渲染,也不会出现任何错误。我非常希望能让代码的所有功能都正常工作,麻烦各位帮忙分析一下问题所在!
我的环境
- 设备:Surface Pro 8
- 系统:Windows 11(已完全更新)
- 已安装的相关库:statsmodels、matplotlib、scipy,且已更新pip
问题代码
import pandas as pd import plotly.express as px # Load the dataset df = pd.read_csv('insurance.csv') # Create scatter plot with trendline and hover data fig = px.scatter( df, x='bmi', y='charges', color='smoker', trendline='ols', # Add linear regression trendline hover_data=['age'], # Include age in hover tooltip title='BMI vs Charges by Smoker Status with Trendline', labels={'bmi': 'BMI', 'charges': 'Charges ($)', 'smoker': 'Smoker'}, opacity=0.6 ) fig.show()
报错信息
ImportError Traceback (most recent call last) Cell In[2], line 13 8 df = pd.read_csv('insurance.csv') 11 # Create scatter plot with trendline and hover data ---> 13 fig = px.scatter( 14 15 df, 16 17 x='bmi', 18 19 y='charges', 20 21 color='smoker', 22 23 trendline='ols', # Add linear regression trendline 24 25 hover_data=['age'], # Include age in hover tooltip 26 27 title='BMI vs Charges by Smoker Status with Trendline', 28 29 labels={'bmi': 'BMI', 'charges': 'Charges ($)', 'smoker': 'Smoker'}, 30 31 opacity=0.6 32 33 ) 36 fig.show() File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\plotly\express\_chart_types.py:69, in scatter(data_frame, x, y, color, symbol, size, hover_name, hover_data, custom_data, text, facet_row, facet_col, facet_col_wrap, facet_row_spacing, facet_col_spacing, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, orientation, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, symbol_sequence, symbol_map, opacity, size_max, marginal_x, marginal_y, trendline, trendline_options, trendline_color_override, trendline_scope, log_x, log_y, range_x, range_y, render_mode, title, subtitle, template, width, height) 14 def scatter( 15 data_frame=None, 16 x=None, (...) 63 height=None, 64 ) -> go.Figure: 65 """ 66 In a scatter plot, each row of `data_frame` is represented by a symbol 67 mark in 2D space. 68 """ ---> 69 return make_figure(args=locals(), constructor=go.Scatter) File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\plotly\express\_core.py:2674, in make_figure(args, constructor, trace_patch, layout_patch) 2671 elif args["ecdfnorm"] == "percent": 2672 group = group.with_columns((nw.col(var) / group_sum) * 100.0) -> 2674 patch, fit_results = make_trace_kwargs( 2675 args, trace_spec, group, mapping_labels.copy(), sizeref 2676 ) 2677 trace.update(patch) 2678 if fit_results is not None: File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\plotly\express\_core.py:430, in make_trace_kwargs(args, trace_spec, trace_data, mapping_labels, sizeref) 427 trace_patch["x"] = trace_patch["x"].to_numpy() 429 trendline_function = trendline_functions[attr_value] --> 430 y_out, hover_header, fit_results = trendline_function( 431 args["trendline_options"], 432 sorted_trace_data.get_column(args["x"]), # narwhals series 433 x.to_numpy(), # numpy array 434 y.to_numpy(), # numpy array 435 args["x"], 436 args["y"], 437 non_missing.to_numpy(), # numpy array 438 ) 439 assert len(y_out) == len( 440 trace_patch["x"] 441 ), "missing-data-handling failure in trendline code" 442 trace_patch["y"] = y_out File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\plotly\express\trendline_functions\__init__.py:42, in ols(trendline_options, x_raw, x, y, x_label, y_label, non_missing) 36 if k not in valid_options: 37 raise ValueError( 38 "OLS trendline_options keys must be one of [%s] but got '%s'" 39 % (", ".join(valid_options), k) 40 ) ---> 42 import statsmodels.api as sm 44 add_constant = trendline_options.get("add_constant", True) 45 log_x = trendline_options.get("log_x", False) File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\statsmodels\api.py:76 1 __all__ = [ 2 "BayesGaussMI", 3 "BinomialBayesMixedGLM", (...) 72 "__version_info__" 73 ] ---> 76 from . import datasets, distributions, iolib, regression, robust, tools 77 from .__init__ import test 78 from statsmodels._version import ( 79 version as __version__, version_tuple as __version_info__ 80 ) File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\statsmodels\distributions\__init__.py:7 2 from .empirical_distribution import ( 3 ECDF, ECDFDiscrete, monotone_fn_inverter, StepFunction 4 ) 5 from .
注:报错信息末尾有截断,但核心问题出现在导入statsmodels.api时
我已经确认自己安装了statsmodels,但还是出现这个错误,有没有哪位大佬能帮我找出问题所在呀?
内容来源于stack exchange
相关产品推荐
相关产品推荐

