我有一个plot_graph()函数,可将熊猫数据帧绘制为折线图。
def plot_graph(df):
ax = plt.gca()
#df["Date"].dt.strftime("%m/%d/%y")
#df["date"] = df["date"].astype('datetime64[ns]')
print(df['date'])
df.plot(kind='line', x='date', y='Actual', ax=ax)
df.plot(kind='line', x='date', y='Expected', color='red', ax=ax)
ax.xaxis.set_major_locator(plt.MaxNLocator(3))
plt.savefig("fig1.png")
我以这种格式传递熊猫数据框
date actual expected
2019-11 20 65
2019-12 35 65
当我绘制折线图时,x轴标签无法正确显示为(yyyy-mm)格式。我相信它是日期格式。所以我尝试将其转换为日期。我尝试了所有选项(在代码中有注释),似乎没有任何效果。任何建议将不胜感激。
答案 0 :(得分:1)
尝试一下:
List<User> usersModified = users.stream().filter(e-> e.getAge()>25).collect(Collectors.toList());
usersModified.forEach(e-> modify(e));
我认为使用import pandas as pd
import matplotlib.dates as mdates
def plot_graph(df):
ax = plt.gca()
df['date'] = pd.to_datetime(df['date']).dt.date
df.plot(kind='line', x='date', y='actual', ax=ax)
df.plot(kind='line', x='date', y='expected', color='red', ax=ax)
ax.xaxis.set_major_locator(mdates.MonthLocator())
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) #to explicitly set format
plot_graph(df)
是最好的选择,但是似乎matplotlib.dates
需要将日期设置为 date 而日期时间(或字符串)。如果您直接通过df.plot()
进行绘制,则不需要这样做。 More here。
答案 1 :(得分:1)
参考Matplotlib: Date tick labels和Formatting date ticks using ConciseDateFormatter
请注意,index
列为日期时间格式。要将列转换为日期时间,请使用df.date = pd.to_datetime(df.date)
df.plot()
具有类似array([13136, 13152, 13174, 13175], dtype=int64)
的刻度位置。我实际上不知道这些数字是如何得出的,但是它们会导致某些matplotlib轴和日期格式设置方法出现问题,这就是为什么我将图从df.plot
更改了。
sns.lineplot
和plt.plot
的刻度位置是日期时间array([737553., 737560., 737567., 737577., 737584., 737591., 737598., 737607.]
的顺序表示。
import pandas as pd
import numpy as np # for test data
from datetime import datetime # for test data
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
# synthetic data with date as a datetime
np.random.seed(365)
length = 700
df = pd.DataFrame(np.random.rand(length, 2) * 10, columns=['Actual', 'Expected'], index=pd.bdate_range(datetime.today(), freq='d', periods=length).tolist()).reset_index()
# display(df.head())
index Actual Expected
0 2020-07-16 9.414557 6.416027
1 2020-07-17 6.846105 5.885621
2 2020-07-18 5.438872 3.680709
3 2020-07-19 7.666258 3.050124
4 2020-07-20 4.420860 1.104433
# function
def plot_graph(df):
# df.date = pd.to_datetime(df.date) # if needed and date is the column name
fig, ax = plt.subplots()
months = mdates.MonthLocator() # every month
months_fmt = mdates.DateFormatter('%Y-%m') # format
ax.plot('index', 'Actual', data=df)
ax.plot('index', 'Expected', data=df, color='red')
# format the ticks
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
plt.xticks(rotation=90)
plt.legend()
plt.show()
plot_graph(df)