Matplotlib: how to set only min and max values for tics

亡梦爱人 提交于 2021-01-28 11:02:41

问题


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)

Output:

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:


回答1:


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)


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


回答2:


This hacky solution piggybacks on this 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()



来源:https://stackoverflow.com/questions/49065929/matplotlib-how-to-set-only-min-and-max-values-for-tics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!