Matplotlib:如何仅设置tic的最小值和最大值 [英] Matplotlib: how to set only min and max values for tics

查看:114
本文介绍了Matplotlib:如何仅设置tic的最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要绘制的代码非常相似:

I have pretty similar code to plot:

plt.plot(df_tags[df_tags.detailed_tag == tag]['week'], df_tags[df_tags.detailed_tag == tag].tonality)

输出:

但是我想这样只保留x轴的最小值和最大值:

But I want leave only min and max values for x axis this way:

plt.plot(df_tags[df_tags.detailed_tag == tag]['week'], df_tags[df_tags.detailed_tag == tag].tonality)
plt.xticks([df_tags['week'].min(), df_tags['week'].max()])
print (df_tags['week'].min(), df_tags['week'].max())

运气不好,他把第二个星期作为最后一个星期,但是为什么以及如何解决这个问题:

With no luck, he puts second week as a last one, but why and how to fix it:

推荐答案

由于输入数据未知,无法确定答案.解释 所示的少量代码将用于设置刻度标签

This can't be answered with certainty due to the unknown input data. Interpreting the small amount of code that is shown one would go for setting the ticks and labels,

t = [df_tags['week'].min(), df_tags['week'].max()]
plt.xticks(t,t)


解释为什么单独单独 plt.xticks(t)无效的原因:
初始图的轴上有一些刻度位置和刻度标签集,即与 [2018-03,2018-04,2018-05,...] 和相应的刻度标签 [2018]相对应的刻度位置-03,2018-04,2018-05,...] .如果现在仅通过 plt.xticks([2018-03,2018-08])更改刻度位置,则绘图将仅具有两个不同的刻度位置,但仍然使用相同的标签来占据这些位置.因此,第二个标签 2018-04 将占据第二个(也是最后一个)位置.
由于这是不希望的,因此应始终将刻度位置设置为.这是通过 plt.xticks(ticklocations,ticklabels) ax.set_xticks(ticklocations)完成的;ax.set_xticklabels(ticklabels).


To explain why plt.xticks(t) alone does not work:
The inital plot's axis has some tick locations and ticklabels set, i.e. tick locations corresponding to [2018-03, 2018-04, 2018-05,...] and the respective ticklabels [2018-03, 2018-04, 2018-05,...]. If you now only change the tick locations via plt.xticks([2018-03, 2018-08]), the plot will only have two differing tick locations, but still the same labels to occupy those locations. Hence the second label 2018-04 will occupy the second (and last) position.
Since this is undesired, you should always set the tick positions and the ticklabels. This is done via plt.xticks(ticklocations, ticklabels) or ax.set_xticks(ticklocations); ax.set_xticklabels(ticklabels).

这篇关于Matplotlib:如何仅设置tic的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆