![]() |
How does pd.date_range() fit in with axs[].set_xticks() ? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How does pd.date_range() fit in with axs[].set_xticks() ? (/thread-37427.html) |
How does pd.date_range() fit in with axs[].set_xticks() ? - Mark17 - Jun-09-2022 My program works at the moment, but I'm trying to better understand why. These three lines define x-axis tick labels for axs[0] subplot: xtick_labels = pd.date_range(btstats['Date'].iloc[0],btstats['Date'].iloc[-1],20) xtick_labels_converted = xtick_labels.strftime('%Y-%m-%d') axs[0].set_xticks(list(np.linspace(1,len(btstats.index),num=len(xtick_labels_converted))),xtick_labels_converted, rotation=45)The first line gets date range from first and last value of 'Date' column. The second line is necessary to avoid "ConversionError: Failed to convert value(s) to axis units." ax.set_xticks() arguments are list of tick locations, list of tick labels, and rotation amount. Isolated from anything else (e.g. not part of a dataframe), what does it mean to have a DatetimeIndex? Is that just a type of object like a range object or generator object? If I print(type()), then for lines 1 and 2, respectively, I get <class 'pandas.core.indexes.datetimes.DatetimeIndex'> and <class 'pandas.core.indexes.base.Index'>. Why is the first object type not acceptable to line 3 (I'm guessing that's what causes the ConversionError) while the second is? RE: How does pd.date_range() fit in with axs[].set_xticks() ? - deanhystad - Jun-09-2022 set_xticks is expecting a list of str Quote:matplotlib.axes.Axes.set_xticksPandas date_range returns a Datetimeindex. A Datetimeindex is an immutable ndarray-like of datetime64 data Quote:pandas.DatetimeIndexSo when you call pandas.daterange() you are getting back an array of things that look like 64 bit integers, not strings. Do you want a bunch of really big integers appearing as tick labels? RE: How does pd.date_range() fit in with axs[].set_xticks() ? - Mark17 - Jun-09-2022 (Jun-09-2022, 02:58 PM)deanhystad Wrote: ... Definitely not. I'm happy with the way this turns out. I just didn't quite understand how it's working. This helps. Thanks! |