Xticks值与条形图一致

2024-09-27 23:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我把我的x记号设置成横条吗。如图所示,条形图与xtick time值不一致。我已经在下面打印了g01g02的数据值和代码。我已经尝试过这个解决方案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记号一致,但它变为数字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")

Tags: lennpfigplt条形图degreesaxisfontsize
1条回答
网友
1楼 · 发布于 2024-09-27 23:20:19

虽然linked duplicate确实改善了与ha='right'的对齐,但是标签仍然会稍微偏离

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

plt.xticks(rotation=90)

如果将rotation=70ha='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)

output of 3 options

相关问题 更多 >

    热门问题