[Python] Is there a reason why Jupyter Notebook will not display trendlines?

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    The problem I'm having is that my code will not display the trendline, but will give me a huge error message. When I remove the trendline, it displays the scatter plot still without the error message, but I really would like to make sure all parts of my code function. Here's the code in question:

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


    I'm working on a Surface Pro 8 with Windows 11, fully updated. I was told that I do not need to update any libraries but I did update pip. I also have statsmodels, matplotlib, and scipy installed already.

    Error I received:

    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 .edgeworth import ExpandedNormal
    ----> 7 from .discrete import (
    8 genpoisson_p, zipoisson, zigenpoisson, zinegbin,
    9 )
    11 __all__ = [
    12 'ECDF',
    13 'ECDFDiscrete',
    (...) 21 'zipoisson'
    22 ]
    24 test = PytestTester()

    File ~\AppData\Local\Programs\Python\Python313\Lib\site-packages\statsmodels\distributions\discrete.py:5
    3 from scipy.stats import rv_discrete, poisson, nbinom
    4 from scipy.special import gammaln
    ----> 5 from scipy._lib._util import _lazywhere
    7 from statsmodels.base.model import GenericLikelihoodModel
    10 class genpoisson_p_gen(rv_discrete):

    ImportError: cannot import name '_lazywhere' from 'scipy._lib._util' (C:\Users\Jasmine\AppData\Local\Programs\Python\Python313\Lib\site-packages\scipy\_lib\_util.py)

    Continue reading...

Compartilhe esta Página