use*_*106 8 python matplotlib pandas
我正在使用pandas加载CSV数据,其中一列采用格式为'%a%d.%m.%Y'的日期形式(例如'Mon 06.02.2017'),然后尝试制作一些情节,其中x轴根据日期标记.
在绘图过程中出现问题,因为日期标签错误; 例如,CSV/DataFrame中的"Mon 06.02.2017"在绘图轴上显示为"Thu 06.02.0048".
这是一个MWE.这是'data.csv'文件:
Mon 06.02.2017 ; 1 ; 2 ; 3
Tue 07.02.2017 ; 4 ; 5 ; 6
Wed 08.02.2017 ; 7 ; 8 ; 9
Thu 09.02.2017 ; 10 ; 11 ; 12
Fri 10.02.2017 ; 13 ; 14 ; 15
Sat 11.02.2017 ; 16 ; 17 ; 18
Sun 12.02.2017 ; 19 ; 20 ; 21
Mon 13.02.2017 ; 22 ; 23 ; 24
Tue 14.02.2017 ; 25 ; 26 ; 27
Wed 15.02.2017 ; 28 ; 29 ; 30
Thu 16.02.2017 ; 31 ; 32 ; 33
Run Code Online (Sandbox Code Playgroud)
这是解析/绘图代码'plot.py':
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.read_csv(
'data.csv',
sep='\s*;\s*',
header=None,
names=['date', 'x', 'y', 'z'],
parse_dates=['date'],
date_parser=lambda x: pd.datetime.strptime(x, '%a %d.%m.%Y'),
# infer_datetime_format=True,
# dayfirst=True,
engine='python',
)
# DataFrame 'date' Series looks fine
print df.date
ax1 = df.plot(x='date', y='x', legend=True)
ax2 = df.plot(x='date', y='y', ax=ax1, legend=True)
ax3 = df.plot(x='date', y='z', ax=ax1, legend=True)
ax1.xaxis.set_minor_locator(mdates.DayLocator(interval=1))
ax1.xaxis.set_minor_formatter(mdates.DateFormatter('%a %d.%m.%Y'))
ax1.xaxis.grid(True, which='minor')
plt.setp(ax1.xaxis.get_minorticklabels(), rotation=45)
plt.setp(ax1.xaxis.get_majorticklabels(), visible=False)
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
请注意,DataFrame.date系列似乎包含正确的日期,因此它可能是matplotlib问题而不是pandas/parsing错误.
万一它可能很重要(虽然我怀疑),我的语言环境是LC_TIME = en_US.UTF-8.
另外,根据https://www.timeanddate.com/date/weekday.html,06.02.0048当天实际上是星期二,所以绘制的年份实际上甚至不是0048年.
我真的很茫然,感谢任何愿意检查出来的人.
小智 4
虽然我无法真正弄清楚为什么它不起作用,但它似乎与使用 pandas 绘图和仅使用 matplotlib 绘图有关,也许mdates.DateFormatter
...
当我注释掉格式行时,它似乎开始工作:
# ax1.xaxis.set_minor_locator(mdates.DayLocator(interval=1))
# ax1.xaxis.set_minor_formatter(mdates.DateFormatter('%a %d.%m.%Y'))
# ax1.xaxis.grid(True, which='minor')
#
# plt.setp(ax1.xaxis.get_minorticklabels(), rotation=45)
# plt.setp(ax1.xaxis.get_majorticklabels(), visible=False)
Run Code Online (Sandbox Code Playgroud)
Pandas 自动绘制日期工作正常,但调用任何 matplotlib 函数都会破坏日期。仅注释掉#plt.setp(ax1.xaxis.get_majorticklabels(), visible=False)
, 将绘制 Pandas 和 Matplotlib x 轴,并且奇怪的 0048 再次出现:
所以问题依然存在。
但是,您可以通过替换parse_dates=['date']
为index_col=0
、显式创建 matplotlib 图形并更改mdates.DateFormatter
为来规避此问题ticker.FixedFormatter
:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
df = pd.read_csv(
'data.csv',
sep='\s*;\s*',
header=None,
names=['date', 'x', 'y', 'z'],
index_col=0,
date_parser=lambda x: pd.to_datetime(x, format='%a %d.%m.%Y'),
engine='python'
)
ax = plt.figure().add_subplot(111)
ax.plot(df)
ticklabels = [item.strftime('%d-%m-%y') for item in df.index]
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.xticks(rotation='90')
ax.xaxis.grid(True, which='major')
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)