Pandas Dataframe.plot,如何更改x轴标签

时间:2020-08-26 01:38:18

标签: python pandas matplotlib

我正在尝试使用Python / Pandas在条形图上绘制一组长达一年的值。生成的图形非常混乱,我设置xtick标签的尝试不起作用。

我的原始代码:

import datetime as dt
import random
import pandas as pd

#generate year-long list of dates
i = 0
list_of_dates = []
last_date = dt.date(2017, 1, 1)
while i < 365:
    list_of_dates.append(last_date)
    last_date += dt.timedelta(days=1)
    #print(last_date)
    i = i + 1

#generate random values for example
daily_rainfall = []
j = 0
while j < 365:
    daily_rainfall.append(random.randint(0,3))
    j = j + 1
    
#put lists in DF
rainfall_dataframe = pd.DataFrame(list(zip(list_of_dates, daily_rainfall)),columns=["Date","Precipitation"])
rainfall_dataframe = rainfall_dataframe.groupby(["Date"]).sum()

rainfall_dataframe.plot(kind="bar", figsize=(13,7))

返回此:

img1

显然无法使用。因此,我希望它仅按月标记x-ticks。我尝试创建日期时间日期对象列表,但这只是每个月的第一天,但​​是当我尝试将其传递给df.plot()时,它什么也不返回。

xlablist = []
xlablist.append(dt.date(2017, 1, 1))
xlablist.append(dt.date(2017, 6, 1))
xlablist.append(dt.date(2018, 1, 1))

rainfall_dataframe.plot(kind="bar", figsize=(13,7), xticks=xlablist)

返回:

img2

请帮助!

2 个答案:

答案 0 :(得分:0)

您可以使用Date locators

import datetime as dt
import random
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


#generate year-long list of dates
i = 0
list_of_dates = []
last_date = dt.date(2017, 1, 1)
while i < 365:
    list_of_dates.append(last_date)
    last_date += dt.timedelta(days=1)
    #print(last_date)
    i = i + 1

#generate random values for example
daily_rainfall = []
j = 0
while j < 365:
    daily_rainfall.append(random.randint(0,3))
    j = j + 1
    
#put lists in DF
rainfall_dataframe = pd.DataFrame(list(zip(list_of_dates, daily_rainfall)),columns=["Date","Precipitation"])
rainfall_dataframe = rainfall_dataframe.groupby(["Date"]).sum()

rainfall_dataframe.plot(kind="bar", figsize=(13,7))

plt.gca().xaxis.set_major_locator(mdates.MonthLocator())

plt.xticks(rotation=45)

plt.show()

enter image description here

答案 1 :(得分:0)

一种可能的解决方案,使用 MonthLocator 指定要在哪里进行 放置 x 标签和 DateFormatter 来指定标签的格式:

# Imports
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Create source data
np.random.seed(0)
dates = pd.date_range(start='2017-01-01', end='2017-12-31')
rainfall = np.random.randint(0, 20, dates.size)

# Drawing
fig, ax = plt.subplots(figsize=(10, 4))
plt.xlabel('Month')
plt.ylabel('mm')
plt.title('Rainfall 2017')
ax.xaxis.set_major_locator(mdates.MonthLocator())
fmt = mdates.DateFormatter('%b %Y')
ax.xaxis.set_major_formatter(fmt)
ax.bar(dates, rainfall)
plt.setp(ax.get_xticklabels(), rotation=30);

对于上面的源数据,我得到以下图片:

enter image description here