How to set day of year as ticklabels for several years? - python

I'm currently working with some temperature data from a sensor that was active for about 4 months (from December 2018 to March 2019). I'm trying to plot the data; however, my time series currently goes from 350 to 430. How do I make the x-axis ticks start over at 0 once it reaches 365? Or, how can I add ticks that represent months starting at December and going to March?
Current graph:

Let's say you have your matplotlib.pyplot object, e.g. plt. We can use this to change the labels of the x-axis ticks:
xticks = plt.xticks()[0]
plt.xticks(xticks, (xticks % 365))

Related

Matplotlib date index is showing incorrect year in time series, taking it back to 50 years ago

I am trying to plot 2 time series in matplotlib. However, when I use plt.subplots(nrows=2, ncols=1) to plot both charts, the date index is showing 50 years in the past (so 1972 instead of 2022) even though the day and month are correct.
On the other hand, if I plot each time series separately without plt.subpots(nrows=2, ncols=1), I would get the year correct.
I attached a snapshot whereby if you check the x-axis, 1970 should be 2020, 1971 should be 2021, and so on.
Here's my code:
# PLotting
if plot:
legend_loc = 'upper right'
figsize = (20,12)
title_pad = 20
fig, ax = plt.subplots(figsize=figsize, nrows=2, ncols=1, sharex=True)
ax[0].plot(weighted_track_record, label=weighted_track_record.columns)
ax[0].legend(loc=legend_loc)
ax[0].set_title('Cryptocurrency Weight (No Rebalancing)', fontweight='bold', color=good_color, pad=title_pad)
ax[1].plot(portfolio_vs_benchmark, label=portfolio_vs_benchmark.columns)
ax[1].legend(loc=legend_loc)
ax[1].set_title(f'Portfolio Value vs {benchmark_id.upper()}', fontweight='bold', color=good_color, pad=title_pad)
# Format x-axis
ax[1].xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax[1].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.xticks(rotation=90)
Note that both data frames weighted_track_record and portfolio_vs_benchmark share the exact same date index.
Thanks!
There seem to be some interaction between Pandas and Matplotlib's date handling. (e.g. https://github.com/pandas-dev/pandas/issues/34850) You might want to try to update both to the latest versions and see if that helps

Is it possible to plot by date and time on the x axis with mathplotlib instead of defaulting to day?

I have a dataframe that's in the format
date
class
01/06/2019 17:45
1
01/06/2019 20:23
2
03/06/2019 06:56
1
I'm trying to plot the changes in class against time using the code below
plt.plot_date(x, y, linestyle='solid')
plt.gcf().autofmt_xdate()
date_format = mpl_dates.DateFormatter('%d-%m-%Y')
plt.gca().xaxis.set_major_formatter(date_format)
plt.tight_layout()
However the result is, well, a mess. There are numerous entries for each day separated by time but the graph is squashing down the x axis to only show the days
Is it possible to expand it so it uses day and time or even day and time in bins?

how to create a tidy x-axis of datetime indexes of a data for my plot

I'm plotting a dataframe which its index is of type datetime (like 2018-05-29 08:20:00).
I slice the data based on last hour and last day and last week and last month and then I plot them.
The data is collected every one minuet. So, the index of each row differs only one minute.
When I plot the data for last hour, the x axis is plotted like:
Or, for the last month it is like:
which is clean and readable. But, when I plot the last day data the x-axis index is like:
Why it is overlapped? how to fix it?
the codes to plot these time frames are the same, just the given dataframe is changed:
self.canvas.axes.plot(df_day.index, df_day.loc[:, item], linestyle="None", marker='.')
# or df_month or df_week or df_hour
how to make a the x-axis index as the format that I want?
I want it to be printed as hour:minute for last hour, or day hour:minute for last day.
I tried the links, but none of them helped:
Customizing Ticks
matplotlib: how to prevent x-axis labels from overlapping each other
I tried
self.canvas.axes.xaxis.set_major_formatter(self.major_formatter, self.canvas.axes.get_xticklabels())
#ticker.FuncFormatter
def major_formatter(x, pos):
return datetime.datetime.fromtimestamp(x.day / 1e3)
but it returned int46 in x variable, so it wasn't helping.
from the first answer to How to plot day and month which is also an answer from question owner I found the solution:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(date, price , label="Price")
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
or in my case:
self.canvas.axes.xaxis.set_major_formatter(mdates.DateFormatter('%d-%b'))
from strftime() and strptime() Format CodesĀ¶, one can learn about formats of dates and times.

Changing X-axis DateTime Intervals in Matplotlib

I browsed over stack overflow and found some matching questions, but I could not gather much from them.
I have a dataset as shown in the image above.
The dataset consists of Sales figures from Jan 1949 to Dec 1960. I want to plot the Date vs Sales graph. My code returned the following graph.
The X-axis shows only intervals of 2 years. I want the x-Axis to display at uniform intervals through the date range of Jan 1949 to Dec 1960 (as shown in the dataset above), rotated in a vertical format to accomodate more xticks. How can I do that?
https://matplotlib.org/3.1.0/api/dates_api.html#matplotlib.dates.MonthLocator i.e. something like:
import matplotlib.dates as mdates
...
ax.xaxis.set_major_locator(mdates.MonthLocator())

X axis doesn't show when plotting dataframe [duplicate]

This question already has answers here:
Changing the tick frequency on the x or y axis
(13 answers)
Closed 4 years ago.
Hi I have a dataframe with dates as index as shares as columns
I want to plot a particular share using dates as x axis.
The series I want to plot is :
df['APPL']=
Date
2018-10-29 24.903347
2018-10-30 25.165384
2018-10-31 25.087744
2018-11-01 24.777180
...
2018-12-06 25.709999
But when I plot it out with df['APPL'].plot(use_index=True), the xasix is not showing.
Then I tried plt.plot(df.index,df['APPL']), the interval of x axis is too small for it to be read. .
How can I increase the interval to show every 10 days for example?
You can rotate:
plt.xticks(rotation=90)
Demo:
plt.plot(df.index,df['APPL'])
plt.xticks(rotation=90)
After rotating, the text would be rotated to 90 degrees.
And if you prefer:
plt.plot(df.index,df['APPL'])
plt.xticks(rotation=45)
Test which you like.
Found to the solution, this code changes the interval to 3 days.
Kudos to #U9-Forward and #wwii for pointing out my index was not datetime format.
df.index=pandas.to_datetime(df.index)
ax = df['APPL'].plot()
# set monthly locator
ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
# set font and rotation for date tick labels
plt.gcf().autofmt_xdate()

Categories

Resources