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!

Arun
  • 2,222
  • 7
  • 43
  • 78

2 Answers2

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

Max
  • 12,794
  • 30
  • 90
  • 142
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'])
manu190466
  • 1,557
  • 1
  • 9
  • 17