简体   繁体   English

pandas / matplotlib:如何在 plot 的 x 轴上显示所有年份?

[英]pandas / matplotlib : How do I show all years on the x-axis of my plot?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.markers as markers
from datetime import datetime as dt

df = pd.DataFrame(
    {
        'date': ['2011-01-01', '2011-02-01', '2012-01-01', '2012-02-01', ],
        'amount': [100, 200, 250, 150,],
    }
)
df.date = pd.to_datetime(df.date)

df_TotalDay = df[['date','amount']].copy(deep=True)
df_TotalDay = df_TotalDay.groupby('date').amount.sum()
df_TotalDay

fig, ax = plt.subplots(figsize=(15,5))
ax.plot(df_TotalDay.index, df_TotalDay.values)
plt.xticks([x for x in df_TotalDay.index])
plt.show()

简单的情节

In the plot above, I just want to display the unique year.在上面的plot中,我只是想显示唯一的年份。 Here, it would just be '2011' and '2012' instead of the actual dates.在这里,它只是“2011”和“2012”而不是实际日期。

I've tried我试过了

plt.xticks([x for x in df_TotalDay.index.year.unique()])

but this didn't work.但这没有用。

I know this looks a bit silly with the DataFrame above but my actual DataFrame is quite large and when I plot my data, it looks like this:我知道上面的 DataFrame 看起来有点傻,但我的实际 DataFrame 相当大,当我的数据为 plot 时,它看起来像这样:

实际情节

In the plot above, matplotlib is not listing every year on the x-axis.在上面的 plot 中,matplotlib 并不是每年都在 x 轴上上市。 I would like to include the missing years.我想包括丢失的年份。

You are very close.你很亲密。 You should generate all the dates you want to show and then add to xticks:您应该生成所有要显示的日期,然后添加到 xticks:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        'date': ['2011-01-01', '2013-02-01', '2016-01-01', '2018-02-01', ],
        'amount': [100, 200, 250, 150,],
    }
)
df.date = pd.to_datetime(df.date)
df_TotalDay = df[['date','amount']].copy(deep=True)
df_TotalDay = df_TotalDay.groupby('date').amount.sum()

fig, ax = plt.subplots(figsize=(15,5))
ax.plot(df_TotalDay.index, df_TotalDay.values)
plt.xticks(pd.date_range(df_TotalDay.index.min(), df_TotalDay.index.max(), freq='YS'))
plt.show()

To show only year, you could use要仅显示年份,您可以使用

import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

在此处输入图像描述

An alternative to Z Li answer is to use matplotlibs dates.YearLocator Z Li 答案的替代方法是使用 matplotlibs dates.YearLocator

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from datetime import datetime as dt

df = pd.DataFrame(
    {
        'date': ['2011-01-01', '2011-02-01', '2012-01-01', '2012-02-01', ],
        'amount': [100, 200, 250, 150,],
    }
)
df.date = pd.to_datetime(df.date)

df_TotalDay = df[['date','amount']].copy(deep=True)
df_TotalDay = df_TotalDay.groupby('date').amount.sum()

fig, ax = plt.subplots(figsize=(15,5))
ax.plot(df_TotalDay.index, df_TotalDay.values)
ax.set_xlabel('Year')
ax.minorticks_off()
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM