matplotlib MonthLocator first x-label - matplotlib

How can I change the first x-label in this chart? So the first month is March instead of February.
incorrect:
correct:
ax.bar(x_col,y_col, color=colors_vs, width=18, edgecolor='black')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m-%Y'))
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=4))
plt.tight_layout()

Related

Seaborn - Change the X-Axis Range (Date field)

how can I change the x-axis so that I begin on January 1 2022? I don't want to set the other side of the bound. The aim here is to create a YTD chart. Thanks! (Data type for the x-axis field 'Date_reported' is a Dtype datetime64[ns]) (ps: does anyone know why my figsize statement isn't working? I'm aiming for the 15 by 8 siz but it doesn't seem to work.
sns.relplot(kind='line', data=df_Final, x='Date_reported', y='New_cases_Mov_avg',
hue='Continent', linewidth=1, ci=None)
sns.set_style("white")
sns.set_style('ticks')
plt.xlabel("Date Reported")
plt.ylabel("New Cases (Moving Average)")
plt.figure(figsize=(15,8))
You could define your figure and ax beforehand, set the figsize and then plot. Doing so, you have to go with lineplot instead of relplot.
ax.set_xlim will define the left boundary, fig.autofmt_xdate rotates the x labels.
fig, ax = plt.subplots(figsize=(15,8))
sns.lineplot(data=df_Final, x='Date_reported', y='New_cases_Mov_avg',
hue='Continent', linewidth=1, ci=None, ax=ax)
sns.set_style("white")
sns.set_style('ticks')
ax.set_xlabel("Date Reported")
ax.set_ylabel("New Cases (Moving Average)")
ax.set_xlim(datetime.date(2022, 1, 1))
fig.autofmt_xdate()

How to set x-axis in every 10 years

i have a problem with plot time series data. I want show x-axis in every 10 years but I can only display it every year. Anyone can provide a solution about this??
fig,ax = plt.subplots(figsize=(11,4))
ax.plot(t, data, '0.1', label ='Data')
ax.plot(t, df_filt, 'C1', label='Lowpass Filter, cutoff=50 days')
ax.set_ylabel('Length of Day')
ax.set_xlabel('Time')
ax.legend()
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.grid(True)
YearLocator takes an argument base= to specify the period between ticks
example:
import matplotlib.dates as mdates
t = mdates.drange(mdates.datetime.date(1900,1,1), mdates.datetime.date(2020,12,31), delta=mdates.datetime.timedelta(days=365))
data = np.random.random(size=t.shape)
fig, ax = plt.subplots()
ax.plot(t, data, '0.1', label ='Data')
ax.set_ylabel('Length of Day')
ax.set_xlabel('Time')
ax.legend()
ax.xaxis.set_major_locator(mdates.YearLocator(base=10))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.grid(True)
EDIT
if you want the dates to start on a non multiple of the base, then you have two solutions that I can think of.
The correct solution is to follow the advice in this answer
But, a simpler solution could be to set yearly ticks, but only display one out of every tick
code:
ax.xaxis.set_major_locator(mdates.YearLocator(base=1))
ax.margins(x=0) # so that the axis starts at the minimum date
ax.set_xticks(ax.get_xticks()[::10]) # only show one every 10 years

xticks are not getting displayed matplotlib

I have a block of code to plot 2 columns vs 1 column as a Line graph.
The Year, Month values (xticks) are not getting displayed in my plot for this simple block of code. Where am I going wrong?
Also, I get the same result with or without plt.subplots? Need an explanation on this, please.
plt.subplots(1, sharex=True)
df.col1.groupby([df["timestamp"].dt.year,df["timestamp"].dt.month]).mean()
.plot('line')
df.col2.groupby([df["timestamp"].dt.year,df["timestamp"].dt.month]).mean()
.plot('line').set_ylim(0, )
plt.title('Title')
plt.ylabel('ylabel')
plt.xlabel('(Year, Month)')
plt.legend(('col1', 'col2'))
plt.figure(figsize=(15,8))

How to force a time series to plot on the whole year, when data is only a few months

I have multiple time series each having a different beginning and end time. When I plot them using pandas and matplotlib I get nice graphs beginning from t0 and ending at tx for each individual series. I know that I cannot plot different length series in one plot, but i would like to at least view them with the months lining up.
For example, say I have two series: 1, begins April and ends September, 2 begins February and ends December.
How do visualize them so that each series is plotted on a yearly graph (Jan to Dec) even though the data does not span those dates? I want to see them one above the other they lining up according to months.
I have it like this so far, with xlim=('jan', 'dec'), but I just get blank plots
for dfl in dfl_list[0:2]:
dfl.plot(x='DateTime', y=['VWCmax', 'VWCmin'],
ax=p1, fontsize=15, xlim=('Jan', 'Dec'))
p1.set_title('Time vs VWC', fontsize=15)
p1.set_ylabel('VWC (%) ' + '{}'.format(imei), fontsize=15)
p1.set_xlabel('Time Stamp', fontsize=15)
I've also tried xticks instead of xlim, but I also get blank plots.
The problem that I was having was that I thought that the argument for xlim could be be the strings 'Jan', and 'Dec', this ended up returning blank graphs because pyplot did not know how to fit a graph on string type. the solution is that xlim has to be passed datetime arguments:
for dfl in dfl_list[0:2]:
dfl.plot(x='DateTime', y=['VWCmax', 'VWCmin'],
ax=p1, fontsize=15, xlim=(datetime(2017,1,1), datetime(2017,12,31))
p1.set_title('Time vs VWC', fontsize=15)
p1.set_ylabel('VWC (%) ' + '{}'.format(imei), fontsize=15)
p1.set_xlabel('Time Stamp', fontsize=15)

horizontally centered xlabels for pandas timeseries plotting

When plotting a Series with a PeriodIndex, pandas always locates the xlabels on the beginning of a Period:
DATA = pd.Series(np.random.randn(120), index=pd.period_range("2013-01", "2012-12", freq="M"))
DATA.plot(ax=plt.gca())
So in this case, the annual labels (2003, ... 2012) are located at the first of January of each year. How can I have the annual labels centered horintally, while keeping the xticks at their places?
So in my example, I want the major_xticks located on each Jan 1st, but the label "2012" be centered between 2012-01-01 and 2013-01-01.