我是Python初学者并尝试使用pyplot绘制数据框。我在过去7天内通过设备从BigQuery中提取了一些数据,看起来像这样:
date device visits
0 20180124 mobile 115702
1 20180125 mobile 105954
2 20180129 mobile 113124
3 20180127 mobile 127296
4 20180128 mobile 154099
5 20180126 mobile 103966
6 20180130 mobile 104010
7 20180130 tablet 19014
8 20180129 tablet 21420
...
我想将每日访问量绘制成折线图,每个设备都有一行,我下面的当前代码生成一个图表,其中一行看起来像乱码意大利面 - 如何告诉pyplot如何显示数据?
到目前为止,这是我的代码:
from pandas.io import gbq
import matplotlib.pyplot as plt
import pandas as pd
pkey='xxx.json'
project_id = "xxx"
query = """
#standardSQL
SELECT date,
device.devicecategory AS device,
SUM(totals.visits) AS visits
FROM `xxx.ga_sessions_20*` AS t
WHERE parse_date('%y%m%d', _table_suffix) between
DATE_sub(current_date(), interval 3 day) and
DATE_sub(current_date(), interval 1 day)
GROUP BY date, device
"""
results = gbq.read_gbq(query, project_id=project_id, dialect='standard', private_key=pkey)
df = pd.DataFrame(results)
df.sort_values(by='date', ascending=True)
fdate = pd.to_datetime(df['date'], format="%Y%m%d")
print(df)
plt.plot(fdate, df['visits'])
plt.ylabel('Sessions')
plt.xlabel('Date')
plt.show()