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

如何在Matplotlib(Python)中修改单个指定名称刻度的字体大小

Target a Specific X-Tick Label to Adjust Its Font Size (Without Changing Others)

Got it, let's fix this problem neatly! Since the position of the "Underneath Screen" tick can shift with your data, we can't rely on hardcoding its index—instead, we'll target it directly by its label text. Here's how to do this with the most common visualization libraries:

For Matplotlib/Seaborn

Both libraries use Matplotlib's underlying axis system, so this method works for both:

  1. First, grab your plot's Axes object (if you don't already have it, use plt.gca() to get the current axes).
  2. Loop through all x-tick labels, check for the target text, and adjust its font size (and optionally rotation to avoid overlapping):
import matplotlib.pyplot as plt
import seaborn as sns

# Example plot (replace with your actual data/plot code)
df = sns.load_dataset("tips")
# Simulate your long label scenario
df["day"] = df["day"].replace("Thur", "Underneath Screen")
ax = sns.barplot(x="day", y="total_bill", data=df)

# Get all x-tick labels
xticks = ax.get_xticklabels()

# Target the specific label
for tick in xticks:
    if tick.get_text() == "Underneath Screen":
        tick.set_fontsize(8)  # Set your desired smaller font size here
        tick.set_rotation(30)  # Optional: Rotate to prevent overlap
plt.tight_layout()
plt.show()

For Plotly

If you're using Plotly (Express or Graph Objects), you can conditionally format the target tick using inline HTML styling:

import plotly.express as px

# Example data
df = px.data.tips()
df["day"] = df["day"].replace("Thur", "Underneath Screen")

fig = px.bar(df, x="day", y="total_bill")

# Update x-axis ticks: set global font size, then adjust the target label
fig.update_xaxes(
    tickfont=dict(size=12),  # Global font size for all ticks
    ticktext=[
        # Use inline HTML to shrink the target label
        f"<span style='font-size:8px'>{label}</span>" if label == "Underneath Screen" else label
        for label in df["day"]
    ],
    tickmode="array",
    tickvals=df["day"]
)

fig.show()

Key Takeaway

The core idea is to match the tick by its text content instead of its position. This way, no matter how your data order changes, the code will always find and adjust the right tick without messing up the readability of other labels.

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

火山引擎 最新活动