matplotlib刻度线与数据点不对齐

编程入门 行业动态 更新时间:2024-10-28 12:30:13
本文介绍了matplotlib刻度线与数据点不对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经修改了示例,但似乎是 x 刻度线位置如果设置nbins = 10不正确!但如果设置 nbins=5,它工作正常.我怎么了?

I have modified the example but it seems the x tick mark position not correct if set nbins=10! but it works fine if set nbins=5. what's wrong with me?

#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from time import mktime from datetime import datetime from matplotlib.ticker import MaxNLocator #%matplotlib inline #-----------------------------------------# def main(): ticks = [ "9-28 11:07:57.435", "9-28 11:10:00.123", "9-28 11:40:00.654", "9-28 11:50:00.341", "9-28 12:00:00.773"] y = np.array([10, 12, 9, 15, 11]) x = [mktime(datetime.strptime("2014-"+i, "%Y-%m-%d %H:%M:%S.%f").timetuple()) for i in ticks] plt.stem(x,y) plt.xticks(x, ticks,rotation=25,ha='right') plt.gca().xaxis.set_major_locator(MaxNLocator(nbins=10, prune = 'lower')) plt.gca().spines['right'].set_color('none') plt.gca().spines['top'].set_color('none') plt.gca().spines['left'].set_smart_bounds(True) plt.gca().spines['bottom'].set_smart_bounds(True) plt.gca().xaxis.set_ticks_position('bottom') plt.gca().yaxis.set_ticks_position('left') plt.show() return #-----------------------------------------# if __name__ == "__main__": main()

推荐答案

当您指定 plt.xticks 时,它所做的是将刻度定位器设置为 FixedLocator,允许您明确放置刻度.当您将刻度定位器分配给 MaxNLocator 时,您将覆盖显式刻度位置.

When you specify plt.xticks, what it does is set the tick locator to a FixedLocator, allowing you to place the ticks explicitly. When you then assign the tick locator to a MaxNLocator, you override the explicit tick placement.

要获得最多 N 个刻度,您可以从刻度列表中提取 N 个值并将它们传递给 xticks,无需手动设置定位器.例如,这些行从您当前的 5 个列表中提取了 3 个刻度.

To get a maximum of N ticks, you can pull N values from your ticks list and just pass those to xticks, and eliminate setting the locator manually. These lines pull 3 ticks out of your current list of 5 as an example.

inds = np.linspace(0,len(ticks)-1,3).astype(int) plt.xticks(np.array(x)[inds], np.array(ticks)[inds],rotation=25,ha='right')

更多推荐

matplotlib刻度线与数据点不对齐

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

发布评论

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

>www.elefans.com

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