Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 880
Rocketq Avatar asked Oct 18 '25 17:10

Rocketq


2 Answers

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).
like image 61
ImportanceOfBeingErnest Avatar answered Oct 21 '25 07:10

ImportanceOfBeingErnest


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

like image 20
Scratch'N'Purr Avatar answered Oct 21 '25 06:10

Scratch'N'Purr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!