matplotlib:在次要标签下绘制主要刻度线标签

编程入门 行业动态 更新时间:2024-10-27 14:25:33
本文介绍了matplotlib:在次要标签下绘制主要刻度线标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这似乎应该很简单-但我看不到该怎么做:

This seems like it should be easy - but I can't see how to do it:

我在X轴上有时间图.我想设置两组刻度线,次要刻度线显示一天中的小时,主要刻度线显示日期/月份.所以我这样做:

I have a plot with time on the X-axis. I want to set two sets of ticks, minor ticks showing the hour of the day and major ticks showing the day/month. So I do this:

# set date ticks to something sensible: xax = ax.get_xaxis() xax.set_major_locator(dates.DayLocator()) xax.set_major_formatter(dates.DateFormatter('%d/%b')) xax.set_minor_locator(dates.HourLocator(byhour=range(0,24,3))) xax.set_minor_formatter(dates.DateFormatter('%H'))

这将勾号标记为ok,但是主要勾号标签(日/月)绘制在次要勾号标签的顶部:

This labels the ticks ok, but the major tick labels (day/month) are drawn on top of the minor tick labels:

如何强制将主要刻度标签绘制在次要标签下方?我尝试将换行符(\ n)放在DateFormatter中,但是由于垂直间距不太正确,所以这是一个较差的解决方案.

How do I force the major tick labels to get plotted below the minor ones? I tried putting newline escape characters (\n) in the DateFormatter, but it is a poor solution as the vertical spacing is not quite right.

任何建议将不胜感激!

推荐答案

您可以将axis方法set_tick_params()与关键字pad一起使用.比较下面的示例.

You can use axis method set_tick_params() with the keyword pad. Compare following example.

import datetime import random import matplotlib.pyplot as plt import matplotlib.dates as dates # make up some data x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(100)] y = [i+random.gauss(0,1) for i,_ in enumerate(x)] # plot plt.plot(x,y) # beautify the x-labels plt.gcf().autofmt_xdate() ax = plt.gca() # set date ticks to something sensible: xax = ax.get_xaxis() xax.set_major_locator(dates.DayLocator()) xax.set_major_formatter(dates.DateFormatter('%d/%b')) xax.set_minor_locator(dates.HourLocator(byhour=range(0,24,3))) xax.set_minor_formatter(dates.DateFormatter('%H')) xax.set_tick_params(which='major', pad=15) plt.show()

PS :此示例是从 moooeeeep

以下是上述代码段的呈现方式:

Here's how the above snippet would render:

更多推荐

matplotlib:在次要标签下绘制主要刻度线标签

本文发布于:2023-07-18 08:31:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1142862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标签   刻度   matplotlib

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!