4

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: enter image description here

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: enter image description here

Rocketq
  • 5,423
  • 23
  • 75
  • 126

2 Answers2

7

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).
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
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()

plot

Scratch'N'Purr
  • 9,959
  • 2
  • 35
  • 51