LoginSignup
4
1

More than 3 years have passed since last update.

Twitterの呟き回数を可視化(期間ごとの行数を求める)

Last updated at Posted at 2019-12-07

前記事ではTwitterの用意している機能で保存した過去データをcsvに書き直しました。せっかく作ったcsvですので、これをもとに期間ごとにツイートした回数をグラフにしてみます。
以下の記事を参考にしています。

Pandas で時系列のデータを期間ごとに集計してまとめる https://qiita.com/ihgs/items/2aa5af86ae5c4a60b091

環境
Python3.6.5
Mac OS Mojave 10.14.4

matplotlib==2.2.2
pandas==0.23.0

generate_timeplot.py
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.read_csv('df_text_date.csv', parse_dates=[0], index_col=[0],encoding='utf16',engine='python',names=("date","text"))

csvを読み込む際に、engine = 'python'としないとエラーになりました。

Error in Reading a csv file in pandas[CParserError: Error tokenizing data. C error: Buffer overflow caught - possible malformed input file.]
https://stackoverflow.com/questions/33998740/error-in-reading-a-csv-file-in-pandascparsererror-error-tokenizing-data-c-err

期間内の行数の集計を、新しく追加したカラム'count'(デフォルト値=1)を合計することで行なっています。

generate_timeplot.py
df['count'] = 1
df2 = df.resample('W').sum() 
fig, ax = plt.subplots(figsize=(250,8))

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.bar(df2.index, df2['count'])
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, fontsize=5);
df2.plot(kind='bar')
plt.show()

resampleメソッドの解説はこちらがわかりやすいです。

pandasで時系列データをリサンプリングするresample, asfreq https://note.nkmk.me/python-pandas-time-series-resample-asfreq/

Figure_1.png

大学の授業期間中はツイート数が多い傾向などが読み取れそうです。今回はテキスト内容を全く使っていませんが、形態素解析+ネガポジ判定をうまく行えば気分の浮き沈みの可視化などもできそうですね。
今回のソースコードは以下にあります。
https://github.com/KanikaniYou/plot_tweet_graph

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1