Matplotlib:如何仅为抽搐设置最小值和最大值

问题描述 投票:0回答:2

我有类似的代码来绘制:

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

输出:enter image description here

但我希望这样只留下x轴的最小值和最大值:

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())

没有运气,他把第二周作为最后一周,但为什么以及如何解决它:enter image description here

python python-3.x matplotlib plot axis
2个回答
2
投票

由于未知的输入数据,无法确定地回答这个问题。解释显示的少量代码,用于设置刻度和标签,

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


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).

1
投票

这个hacky解决方案搭载在这个SO post

import pandas as pd
import numpy as np

df = pd.DataFrame({'week': ['2018-01', '2018-02', '2018-03', '2018-04', '2018-05', '2018-06', '2018-07', '2018-08'], 'val': np.arange(8)})

fig, ax = plt.subplots(1,1)
ax.plot(df['week'], df['val'])
for i, label in enumerate(ax.get_xticklabels()):
    if i > 0 and i < len(ax.get_xticklabels()) - 1:
        label.set_visible(False)
plt.show()

plot

© www.soinside.com 2019 - 2024. All rights reserved.