【问题标题】:X-ticks values consistent with bars [duplicate]X-ticks 值与条形图一致 [重复]
【发布时间】:2021-05-09 14:44:34
【问题描述】:

有人可以帮我设置带有条形的 x-ticks。如图所示,这些条与 xtick 时间值不一致。我在下面打印了g01、g02 的数据值和代码。我已经尝试过这个解决方案Python MatplotLib plot x-axis with first x-axis value labeled as 1 (instead of 0)、plt.xticks(np.arange(len(g01))、np.arange(1, len(g01)+1)),虽然条形与 x-ticks 一致,但它会更改为数字 1 到 28。我想要像我的图像中那样的时间段。

g01 = ['2021-02-01 05:00:31', '2021-02-02 00:01:04', '2021-02-03 00:05:09', '2021-02-04 00:05:15', '2021-02-05 00:03:14', '2021-02-06 00:00:25', '2021-02-07 00:04:09', '2021-02-08 00:04:35', '2021-02-09 00:00:00', '2021-02-10 00:02:00', '2021-02-11 00:01:28', '2021-02-12 00:06:31', '2021-02-13 00:00:30', '2021-02-14 00:03:30', '2021-02-15 00:05:20', '2021-02-16 00:00:13', '2021-02-17 00:00:21', '2021-02-18 00:08:02', '2021-02-19 00:00:31', '2021-02-20 00:00:04', '2021-02-21 00:05:05', '2021-02-22 00:02:18', '2021-02-23 00:00:10', '2021-02-24 00:00:38', '2021-02-25 00:00:47', '2021-02-26 00:00:17', '2021-02-27 00:00:28', '2021-02-28 00:03:00']
g02 = [164, 158, 180, 200, 177, 112, 97, 237, 95, 178, 163, 78, 67, 65, 134, 93, 220, 74, 131, 172, 77, 102, 208, 109, 113, 208, 110, 101]

fig = plt.figure()
fig, ax1 = plt.subplots(1,1)
plt.yscale("log")
barlist1=ax1.bar(g01,g02)
for i in range(21):
    barlist1[i].set_color('pink')
degrees = 70
plt.xticks(rotation=degrees)    
plt.xlabel('period', fontsize=14, fontweight="bold")
plt.ylabel('rating values', fontsize=10, fontweight="bold")

【问题讨论】:

标签: python matplotlib


【解决方案1】:

虽然linked duplicate 确实改进了与ha='right' 的对齐方式,但标签仍会略微偏离。

首先注意刻度/标签已正确映射,您可以使用rotation=90(左子图)看到:

plt.xticks(rotation=90)

如果您将rotation=70 与ha='right' 一起使用,请注意标签仍然略有偏移。这是因为 matplotlib 使用文本的边界框进行对齐,而不是文本本身(中心子图):

plt.xticks(rotation=70, ha='right')

要更精确地调整标签,请添加ScaledTranslation 变换(右子图):

from matplotlib.transforms import ScaledTranslation
offset = ScaledTranslation(xt=0.075, yt=0, scale_trans=fig.dpi_scale_trans)
for label in ax1.xaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2020-01-02
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多