matplotlib x轴刻度标签位于数据点前面一个位置[重复]

li9yvcax  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(118)

此问题已在此处有答案

Aligning rotated xticklabels with their respective xticks(6个回答)
上个月关门了。
我有一个seaborn线图,显示两个类别的季度计数变化。问题是x轴标签比数据点提前一个位置。我调整了代码,但没有帮助。
创建示例数据

import pandas as pd
import random
import matplotlib.pyplot as plt
import seaborn as sns

categories = ['A', 'B']
quarters = []
for year in range(2014, 2024):
    for quarter in range(1, 5):
        quarters.append(f"{year}-Q{quarter}")
data = []
for category in categories:
    for quarter in quarters:
        count = random.randint(40000, 500000)
        data.append({'category': category, 'quarter': quarter, 'count': count})
df = pd.DataFrame(data)

创建图表

# Create the lineplot
plt.figure(figsize=(10, 6))
ax = sns.lineplot(x="quarter", y="count", hue="category", data=df, marker="o")
plt.xlabel("Quarter")
plt.ylabel("Count")
plt.xticks(rotation=45)

# Set the x-axis tick positions and labels based on the quarters in the DataFrame
x_positions = range(len(quarters))
ax.set_xticks(x_positions)
ax.set_xticklabels(quarters, rotation=45)  # Display every label

plt.tight_layout()
plt.show()

图表

d6kp6zgx

d6kp6zgx1#

你可能会对你使用的结果更满意

ax.set_xticklabels(quarters, rotation=45, fontdict={'horizontalalignment': 'right'})

它看起来像这样:

在我看来,它把标签推得有点太靠左了。rotation=90的结果更清晰。

bfhwhh0e

bfhwhh0e2#

你对数据没有问题。你的标签被旋转到45度,为了适应这一点,它显示了一点偏离。
下面是代码和图像,旋转=90

# Set the x-axis tick positions and labels based on the quarters in the DataFrame
x_positions = range(len(quarters))
ax.set_xticks(x_positions)
ax.set_xticklabels(quarters, rotation=90)  # Display every label

相关问题