AnyPointSystem (powered by Qiitadon) > 2019-05-06 UI > Radar Chart表示

```txt:動作環境
Ubuntu 18.04 LTs
Jupyter Notebook v5.7.8 
(Python 3.6.7 (default, Oct 22 2018, 11:32:17) )
```

### 関連

- [Qiitadon (Mastodon) > create_app()のto_fileで保存されるclient_id.txtの中身 | AnyPointSystem始めました](https://qiita.com/7of9/items/f8deafc9c301d9e01e2b)
- [AnyPointSystem (powered by Qiitadon) > 2019-04-27 システム設計](https://qiita.com/7of9/items/45aba268f6358541080c)

### 前準備
(2019-05-08改訂)

1. Mastodon.pyのセットアップ
2. japanize_matplotlibのセットアップ
3. アプリの登録 (Qiitadonの開発にて登録「AnyPointSystem」）
4. client_id.txtの生成 (client_idとclient_secret: 手順3の登録情報から)
5. access_token.txtの生成 (手順3の登録情報から)

### 概要

- Qiitadonをデータベースとするポイントシステム
- 今回
    - Radar Chartでの表示
 
### 参考

- [Matplotlibでレーダーチャートを描く（16行）](https://qiita.com/1007/items/80406e098a4212571b2e) by @1007 さん

情報感謝です

### 実装

```py:RadarChart_190506.ipynb
import sys
from mastodon import Mastodon
import datetime
import csv
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import japanize_matplotlib

# [ ] PEP8 checked
#    except for "line too long (81 > 79 characters)"

# 2019-05-06 10:02 shown in Radar Chart
#     - draw in Radar Chart
#     - branched from [Qiitadon_API_190505.ipynb] where Habitat tracker is drawn
# 2019-05-06 08:57
#     - correct date from [UTC] to [JST]
#     - fix bug: calender days had off-by-one-error
# 2019-05-05 10:44
# 2019-05-05 09:18
# ...
# 2019-04-29 08:49
# 2019-04-27 09:17

# reference
# for bullet journal display
#   https://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html

url = "https://qiitadon.com"
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# print(user_toots[0])  # トゥートを全て表示する

NUM_LOOP = 40  # for getting 40 toot each
# NUM_LOOP = 0 # for debug
# NUM_LOOP = 5 # for debug

def isAnyPointData(inlist):
    for elem in inlist:
        # print('***', elem)  # debug
        if 'anypointdata' in elem['name']:
            return True
    return False


def getPointTag(inlist):
    res = []
    for elem in inlist:
        if 'anypointdata' in elem['name']:
            continue
        res += [elem['name']]
    return res


max_id = None
fulllist = []

for loop in range(NUM_LOOP):
    user_dict = mastodon.account_verify_credentials()
    # 40 seems limit as of 2019-04-27
    user_toots = mastodon.account_statuses(user_dict['id'],
                                           max_id=max_id, limit=40)

    max_id = user_toots[-1]['id']
    # print(len(user_toots))
    for idx in range(len(user_toots)):
        # print(user_toots[idx])  # to print what the toot looks like
        atoot = user_toots[idx]['tags']
        atime = user_toots[idx]['created_at']

        # to avoid [TypeError: can't subtract offset-naive and offset-aware datetimes ]
        # https://stackoverflow.com/questions/796008/cant-subtract-offset-naive-and-offset-aware-datetimes
        atime = atime.replace(tzinfo=None)

        if len(atoot) == 0:
            continue
        if not isAnyPointData(atoot):
            continue
        res = getPointTag(atoot)
        fulllist += [[atime, res]]
        print('.', end='')
        # print(res)
        # print(atime)

# for debug
if NUM_LOOP == 0:
    fulllist = [
        [datetime.datetime(2019, 4, 30, 23, 8, 29, 983000), ['中国語学習']],
        [datetime.datetime(2019, 4, 30, 23, 1, 52, 859000), ['英語復習']],
        [datetime.datetime(2019, 4, 30, 13, 25, 46, 588000), ['中国語復習']],
        [datetime.datetime(2019, 4, 30, 13, 1, 31, 340000), ['ツール作成']],
        [datetime.datetime(2019, 4, 30, 12, 58, 27, 258000), ['animalbyaurora']],
        [datetime.datetime(2019, 4, 30, 9, 40, 31, 145000), ['チカッとチカ千花っ']],
        [datetime.datetime(2019, 4, 30, 9, 21, 52, 735000), ['farbymarieueda']],
        [datetime.datetime(2019, 4, 30, 9, 14, 35, 939000), ['queendombyaudora']],
        [datetime.datetime(2019, 4, 30, 9, 10, 58, 67000), ['animalbyaurora']],
        [datetime.datetime(2019, 4, 30, 2, 59, 50, 350000), ['英語復習']],
        [datetime.datetime(2019, 4, 29, 23, 32, 33, 842000), ['grenning学習', 'tdd学習']],
        [datetime.datetime(2019, 4, 29, 23, 27, 7, 216000), ['英語復習']],
        [datetime.datetime(2019, 4, 29, 13, 21, 5, 351000), ['英語学習']],
        [datetime.datetime(2019, 4, 29, 13, 5, 28, 552000), ['chinese']],
        [datetime.datetime(2019, 4, 29, 12, 30, 45, 331000), ['中国語学習']],
        [datetime.datetime(2019, 4, 29, 11, 57, 15, 318000), ['farbymarieueda']],
        [datetime.datetime(2019, 4, 29, 9, 51, 2, 24000), ['チカッとチカ千花っ']],
        [datetime.datetime(2019, 4, 29, 9, 33, 31, 33000), ['queendombyaudora']],
        [datetime.datetime(2019, 4, 29, 9, 32, 7, 586000), ['英語学習']],
        [datetime.datetime(2019, 4, 29, 9, 26, 30, 169000), ['farbymarieueda']],
        [datetime.datetime(2019, 4, 29, 9, 22, 31, 857000), ['animalbyaurora']],
        [datetime.datetime(2019, 4, 29, 1, 30, 51, 103000), ['ツール作成']],
        [datetime.datetime(2019, 4, 29, 1, 29, 41, 267000), ['チカッとチカ千花っ']],
        [datetime.datetime(2019, 4, 28, 23, 25, 35, 632000), ['queendombyaudora']],
        [datetime.datetime(2019, 4, 28, 23, 18, 31, 362000), ['animalbyaurora']],
        [datetime.datetime(2019, 4, 28, 23, 0, 21, 950000), ['英語復習']],
        [datetime.datetime(2019, 4, 28, 12, 36, 59, 80000), ['中国語復習']],
        [datetime.datetime(2019, 4, 28, 3, 34, 23, 115000), ['queendombyaurora']],
        [datetime.datetime(2019, 4, 28, 3, 30, 38, 750000), ['animalbyaurora']],
        [datetime.datetime(2019, 4, 28, 3, 29, 39, 44000), ['中国語学習']],
        [datetime.datetime(2019, 4, 28, 1, 18, 9, 823000), ['grenning学習', 'tdd学習']],
        [datetime.datetime(2019, 4, 28, 1, 17, 45, 883000), ['チョコ食べる']],
    ]

print()  # for new line

# add 1st tag
tagcsv = fulllist[0][1][0]  # 0: 1st toot, 1: tag, 0: expand from list
# print(tagcsv)
for elem in fulllist:
    # print(elem[1])
    atag = elem[1][0]
    if atag not in tagcsv:
        tagcsv += "," + str(elem[1][0])
taglist = tagcsv.split(",")

DAYS_PAST = 40
BASE_DATE = datetime.datetime.now() - datetime.timedelta(days=(DAYS_PAST-1))
BASE_DATE = BASE_DATE.replace(hour=0, minute=0, second=0, microsecond=0)
#print(BASE_DATE)
NUM_GRAPHS = 30
FIG_SIZE = figsize = (12, 20)
NUM_COLORS = 5

# count each item
amax = 1
totalCounts = []
for idx, trgtag in enumerate(taglist):  # loop by target tag
    # wrklist = [0 for i in range(DAYS_PAST)]
    ttlcnt = 0   # total count
    for elem in fulllist:
        adate = elem[0]
        tags = elem[1]
        for atag in tags:
            if trgtag not in atag:
                continue
            elem[0] = elem[0] + datetime.timedelta(hours=9)  # [UTC] to [JST]
            elpsd = (int)((elem[0] - BASE_DATE).total_seconds() / 60 / 60 / 24)
            # wrklist[elpsd] += 1
            ttlcnt += 1
    totalCounts += [ttlcnt]

        
def plot_polar(labels, values, fig):
    # acknowledgemnt: @1007
    #   https://qiita.com/1007/items/80406e098a4212571b2e
    # modified
    #   - show on display not to file
    #   - take [fig] parameter    
    angles = np.linspace(0, 2 * np.pi, len(labels) + 1, endpoint=True)
    values = np.concatenate((values, [values[0]]))  # 閉じた多角形にする    
    ax = fig.add_subplot(111, polar=True)
    ax.plot(angles, values, 'o-')  # 外枠
    ax.fill(angles, values, alpha=0.25)  # 塗りつぶし
    ax.set_thetagrids(angles[:-1] * 180 / np.pi, labels)  # 軸ラベル
    amax = max(values)
    ax.set_rlim(0, amax)

fig = plt.figure(figsize=(8, 8),dpi=200)
plot_polar(taglist, totalCounts, fig)
    
plt.show()

```

### 実行例

![Screenshot from 2019-05-06 10-35-31.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/32870/09ead7b2-8755-306c-b82d-fe9bd503464a.png)


### 用途

- 一週間あたりの取組みの可視化
- 長期間だとポイントの変動が少なく、期待したような効果(*1)はないだろう
    - *1) 良い習慣を促進する