Issue
Could someone please help me to set my x-ticks with bars. The bars are not consistent with xtick time values as you can see in the image. I have printed my data values of g01
, g02
below and code as well. I have tried this solution 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))
although then bars are consistent with x-ticks but it changes to numbers 1 to 28. I want time period like in my image.
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")
Solution
While the linked duplicate does improve the alignment with ha='right'
, the labels will still be slightly off.
First note that the ticks/labels are correctly mapped, which you can see by using rotation=90
(left subplot):
plt.xticks(rotation=90)
If you use rotation=70
with ha='right'
, notice that the labels are still slightly shifted. This is because matplotlib uses the text's bounding box for alignment, not the text itself (center subplot):
plt.xticks(rotation=70, ha='right')
To tweak the labels more precisely, add a ScaledTranslation
transform (right subplot):
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)
Answered By - tdy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.