我花了30多个小时试图解决这个问题,包括在网上搜索。现在我正在接触。
我的环境:Python 3.6.0,pandas 0.20.1,matplotlib 2.0.2,pypyodbc 1.3.4
我正在尝试从SQL Server中绘制数据。除最终绘图外,代码中的所有内容都不起作用,不显示x轴刻度线或任何x轴值。否则,情节看起来是正确的。 x轴是日期字段,格式为YYYY-mm-dd。我已经尝试了几十种变体来使它工作。你看到这段代码有什么问题吗?不介意复杂的查询,我真的不认为这与问题有关。
import pypyodbc
import pandas as pd
import pandas.io.sql
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FormatStrFormatter
months = mdates.MonthLocator() # every month
days = mdates.DayLocator() # every day
daysFmt = FormatStrFormatter('%d')
#Connect to SQL Server databause using Trusted Connection
sql = """SELECT UID, startdate, lastdelivered FROM TABLENAME """
iddf = pandas.io.sql.read_sql(sql, conn)
for UID in range(len(iddf)):
sql = """SELECT impdate, sum(imp) as imps FROM TABLENAME where UID = """
+ str(iddf['UID'].iloc[UID]) + """ and impdate >= '2017-05-01' and impdate
<= '2017-05-15' group by impdate order by impdate"""
df = pandas.io.sql.read_sql(sql, conn)
df.impressions.fillna(value=0, inplace=True)
pd.to_datetime(df['impdate'], format= '%Y-%m-%d')
print (df['impdate']) #Shows the format to be YYYY-mm-dd
ax = (df[['impdate','imps']].plot(kind='line', title="UID: ", figsize=
(10, 10), legend=False, fontsize=10))
ax.set_xlabel("ImpDate", fontsize=12)
ax.set_ylabel("Imps", fontsize=12)
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(daysFmt)
plt.setp(ax.get_xticklabels(),visible = True)
plt.show(ax)
plt.close('all')