如何复用其他脚本代码段?Bokeh对象NameError问题解决
The issue you’re hitting is simple: when you move those title lines to a separate file, the variable p doesn’t exist in that file’s scope—it’s only created in your main script. To fix this, you need to pass the figure object p to a function in your reusable module, so the function can modify its attributes directly.
Here’s a step-by-step solution:
1. Create a Reusable Module
Make a new file (let’s name it plot_styling.py) and define a function that accepts the figure as an argument:
# plot_styling.py def apply_title_style(p): # Your original title styling lines, now using the passed-in p object p.title.text = "Title" p.title.text_color = "Orange" p.title.text_font = "times"
If you want the title text to be customizable instead of hardcoding "Title", add an optional parameter:
# plot_styling.py (customizable version) def apply_title_style(p, title_text="Title"): p.title.text = title_text p.title.text_color = "Orange" p.title.text_font = "times"
2. Use the Function in Your Main Script
In your original script, import the function and call it after creating your figure p:
from bokeh.plotting import figure, show, output_file from plot_styling import apply_title_style # Import the reusable function p = figure() p.circle([1,2,3], [4,5,6]) # Apply the title style by passing p to the function apply_title_style(p) # If using the customizable version: apply_title_style(p, title_text="My Custom Title") show(p) output_file("file.html")
This works because you’re explicitly passing the existing p figure object into the function. The function modifies the attributes of that same object, so there’s no NameError—p is defined in the main script and passed to the function where it’s used.
内容的提问来源于stack exchange,提问作者multigoodverse

