You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

绘制完成后设置Seaborn图表轴属性、样式及字体的方法咨询

Seaborn lmplot: Setting Style and Font for New Python Users

Hey there! Let's walk through each of your requirements clearly, since you're just starting out with Python and Seaborn. Here's how to get your lmplot looking exactly how you want:

1. Correctly Creating the lmplot

First, your initial code is close, but Seaborn recommends explicitly using the data parameter to pass your DataFrame, with x, y, and hue as strings matching your column names. This makes the code more readable and avoids potential errors:

# Replace "x_col", "y_col", "z_col" with your actual column names in df
g = sns.lmplot(data=df, x="x_col", y="y_col", hue="z_col")

2. Setting the "whitegrid" Style

To apply the whitegrid style, you just need to call sns.set_style() before creating your plot. This sets a global style for all subsequent Seaborn plots:

import seaborn as sns

# Set the style first
sns.set_style("whitegrid")

# Then create your plot
g = sns.lmplot(data=df, x="x_col", y="y_col", hue="z_col")

3. Using "Times New Roman" Font

Seaborn builds on Matplotlib, so we can set the font either through Seaborn's own set() function or directly via Matplotlib's rcParams. Both methods work, but the Seaborn way is simpler for beginners:

Option 1: Seaborn's set() function

sns.set(font="Times New Roman")

Option 2: Matplotlib rcParams (for more control)

If you want to customize font settings further (like font size), you can use Matplotlib directly:

import matplotlib.pyplot as plt

plt.rcParams["font.family"] = "Times New Roman"
# Optional: Adjust font size if needed
plt.rcParams["font.size"] = 12

Full Working Example

Putting it all together, your code would look like this:

import seaborn as sns
import matplotlib.pyplot as plt

# Configure style and font first
sns.set_style("whitegrid")
sns.set(font="Times New Roman")

# Create the lmplot
g = sns.lmplot(data=df, x="x_col", y="y_col", hue="z_col")

# Display the plot
plt.show()

A quick note: Make sure "Times New Roman" is installed on your system (it's standard on Windows/Mac, but Linux users may need to install it first). If you run into font issues, you can check available fonts with plt.font_manager.findSystemFonts().

内容的提问来源于stack exchange,提问作者jjameson

火山引擎 最新活动