0

I have a pandas dataframe 'g' having two columns and looks like:

enter image description here

I am trying to plot it using the code:

g.plot(x = 'date', y = 'some_value', kind = 'bar', figsize = (10, 5), legend = False)
plt.xlabel("date")
plt.ylabel("some value")
plt.show()

which produces the following graph: enter image description here

This happens since there are 318 days of data starting on 2018-01-02 and ending on 2018-12-11, all of which are plotted resulting in a messy and unreadable x-axis.

I want to reduce the number of labels on x-axis to contain intervals for say every 15 days. How can I do so?

I found an answer but it talks about replacing the same number of intervals with a custom text which is not my problem. I want to reduce the number of intervals with a custom text.

Thanks!

2 Answers 2

1

manu190466's answer should be the default way to go for time series. If for whatever reason you want something custom, you can always use set_xticklabels to decide which labels to show/hide and what they should be:

import pandas as pd

# Tweak as per desired logic. Entirely up to you what to show
# To hide a label simply return None for it
def my_labels(data):
    # Show only odd-positioned labels
    return ['Custom: '+d[0] if i%2==0 else None for i,d in enumerate(data)]
    

data = [['2021-01-01',1],['2021-01-02',2],['2021-01-03',3]]
df = pd.DataFrame(data,columns=['date','value'])
ax = df.value.plot(xticks=df.index, rot=90)
ax.set_xticklabels(my_labels(data))
ax

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Make your DataFrame a TimeSerie by converting the date column to an pd.datetime index

dt= pd.to_datetime(g['dates'],format="%Y-%m-%d")
g.index=dt

Then matplotlib will auto adjust the x scale and the labels

g.plot( y = ['some_value'])

1 Comment

Please give a reproducible example so I can test my code on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.