使用Seaborn绘制随机游走轨迹图形无显示的技术求助
Hey Carla, great job getting that code set up—exit code 0 means your script ran without errors, so we just need to tweak a few things to make those random walk plots visible. Here are the most common fixes:
1. Add plt.show() to Your Script
This is the #1 reason plots don't appear in standalone Python scripts (unlike Jupyter notebooks). Matplotlib (which Seaborn relies on under the hood) won't automatically render plot windows in script mode—you have to explicitly tell it to display the output.
Just add this line at the very end of your code:
plt.show()
Your full modified code would look like this:
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style="ticks") # Create a dataset with many short random walks rs = np.random.RandomState(4) pos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1) pos -= pos[:, 0, np.newaxis] step = np.tile(range(5), 20) walk = np.repeat(range(20), 5) df = pd.DataFrame(np.c_[pos.flat, step, walk], columns=["position", "step", "walk"]) # Initialize a grid of plots with an Axes for each walk grid = sns.FacetGrid(df, col="walk", hue="walk", palette="tab20c", col_wrap=4, height=1.5) # Draw a horizontal line to show the starting point grid.refline(y=0, linestyle=":") # Draw a line plot to show the trajectory of each random walk grid.map(plt.plot, "step", "position", marker="o") # Adjust the tick positions and labels grid.set(xticks=np.arange(5), yticks=[-3, 3], xlim=(-.5, 4.5), ylim=(-3.5, 3.5)) # Adjust the arrangement of the plots grid.fig.tight_layout(w_pad=1) # Add this line to display the plot! plt.show()
2. Check Your Matplotlib Backend (If plt.show() Doesn't Work)
Sometimes matplotlib is configured to use a "headless" backend (like Agg) that can't display graphical windows. To check your current backend, add this at the start of your script:
import matplotlib print(matplotlib.get_backend())
If the output is Agg or another non-interactive backend, switch to an interactive one (like TkAgg, Qt5Agg, or GTK3Agg) before importing pyplot:
import matplotlib matplotlib.use('TkAgg') # Pick one supported by your operating system import matplotlib.pyplot as plt
3. If You're Running on a Server/Headless Environment
If you're running this code on a server without a graphical interface, you won't be able to pop up a window. Instead, save the plot to a file so you can view it later:
# Replace plt.show() with this (or use both if you want to save and show locally) grid.savefig("random_walk_plots.png", dpi=300)
内容的提问来源于stack exchange,提问作者Carla

