Пример #1
0
def make_japan_heatmap(filename, title, npa1d, populations):
    """ 都道府県別ヒートマップを表示する """
    fig = go.Figure()
    w = 610
    h = 630
    cmap = plt.get_cmap("plasma")
    norm = plt.Normalize(vmin=np.min(npa1d[1:]), vmax=np.max(npa1d[1:]))
    fcol = lambda x: '#' + bytes(cmap(norm(x), bytes=True)[:3]).hex()
    fig.add_trace(go.Scatter(x=[0, w], y=[0, h], mode='markers', marker_opacity=0))
    fig.add_trace(go.Heatmap(x=[0, 0], y=[0, 0], opacity=0,
        z=[np.min(npa1d[1:]), np.max(npa1d[1:])],
        zmin=np.min(npa1d[1:]), zmax=np.max(npa1d[1:]),
        type='heatmap', colorscale='plasma', showscale=True))
    map_cols = {}
    for k, v in populations.items():
        map_cols[v['ja']] = fcol(npa1d[v['code']])
    pict = picture(map_cols)
    axis_template = lambda x: dict(
        range=[0, x], autorange=False, showgrid=False, zeroline=False,
        linecolor='black', showticklabels=False, ticks='')
    fig.update_layout(title=title, xaxis=axis_template(w), yaxis=axis_template(h),
                     showlegend=False, width=w, height=h, autosize=False,
                      margin={"l": 0, "r": 0, "t":40, "b": 0}
                     )
    fig.add_layout_image(dict(
            x=0, sizex=w, y=h, sizey=h, xref="x", yref="y", opacity=1,
            layer="below", sizing="stretch", source=Image.fromarray(pict)))
    show_and_save_plotly(fig, filename, js=False, show=True, image=True, html=False)
Пример #2
0
def jpn_map(prefectures, values, title, cmap_name="Reds", filename=None):
    """
    Show colored Japan prefecture map.
    @prefectures <list/pd.Series[str]>: prefecture name.
    @values <int/float>: value of each prefectures
    @title <str>: title of the figure
    @cmap_name <str>: Please refere to
        - https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
        @filename <str>: filename of the figure, or None (show figure)
    """
    # Prefecture code created in
    # https://www.kaggle.com/lisphilar/eda-of-japan-dataset
    # Primary data: http://nlftp.mlit.go.jp/ksj/gml/codelist/PrefCd.html
    # cf. https://www.japanvisitor.com/japan-travel/prefectures-map
    pref_code_dict = dict([('Hokkaido', 1), ('Aomori', 2), ('Iwate', 3),
                           ('Miyagi', 4), ('Akita', 5), ('Yamagata', 6),
                           ('Fukushima', 7), ('Ibaraki', 8), ('Tochigi', 9),
                           ('Gunma', 10), ('Saitama', 11), ('Chiba', 12),
                           ('Tokyo', 13), ('Kanagawa', 14), ('Niigata', 15),
                           ('Toyama', 16), ('Ishikawa', 17), ('Fukui', 18),
                           ('Yamanashi', 19), ('Nagano', 20), ('Gifu', 21),
                           ('Shizuoka', 22), ('Aichi', 23), ('Mie', 24),
                           ('Shiga', 25), ('Kyoto', 26), ('Osaka', 27),
                           ('Hyogo', 28), ('Nara', 29), ('Wakayama', 30),
                           ('Tottori', 31), ('Shimane', 32), ('Okayama', 33),
                           ('Hiroshima', 34), ('Yamaguchi', 35),
                           ('Tokushima', 36), ('Kagawa', 37), ('Ehime', 38),
                           ('Kochi', 39), ('Fukuoka', 40), ('Saga', 41),
                           ('Nagasaki', 42), ('Kumamoto', 43), ('Oita', 44),
                           ('Miyazaki', 45), ('Kagoshima', 46),
                           ('Okinawa', 47)])
    # Data to dataframe
    df = pd.DataFrame({"Name": prefectures, "Value": values})
    df["Code"] = df["Name"].map(pref_code_dict)
    df["Japanese_name"] = df["Code"].apply(lambda x: japanmap.pref_names[x])
    df = df.set_index("Japanese_name")
    # Color code
    cmap = cm.get_cmap(cmap_name)
    norm = matplotlib.colors.Normalize(vmin=df["Value"].min(),
                                       vmax=df["Value"].max())

    def fcol(x):
        return "#" + bytes(cmap(norm(x), bytes=True)[:3]).hex()

    # Show figure
    plt.xticks(color="None")
    plt.yticks(color="None")
    plt.tick_params(length=0)
    plt.imshow(japanmap.picture(df["Value"].apply(fcol)))
    mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
    mappable._A = []
    plt.colorbar(mappable)
    plt.title(title)
    if filename is None:
        plt.show()
        return None
    plt.savefig(filename, bbox_inches="tight", transparent=False, dpi=300)
    plt.clf()
    return None
Пример #3
0
    def create_figure_y(self):
        cmap = plt.get_cmap('binary')
        norm = plt.Normalize(vmin=9.0, vmax=19.0)
        fcol = lambda x: '#' + bytes(cmap(norm(x), bytes=True)[:3]).hex()
        plt.colorbar(plt.cm.ScalarMappable(norm, cmap))
        plt.title('y mean')
        df = self.data['Y'].apply(fcol)

        # indexを振り直す
        df.index = df.index + 1

        plt.imshow(picture(df))
        plt.show()
        plt.close()
Пример #4
0
def whitejapanmap():
    import urllib
    import base64
    import io
    import matplotlib.pyplot as plt
    from japanmap import picture
    plt.rcParams['figure.figsize'] = 6, 6
    plt.imshow(picture())
    fig = plt.gcf()
    buf = io.BytesIO()
    fig.savefig(buf, format='png')
    buf.seek(0)
    string = base64.b64encode(buf.read())
    uri = urllib.parse.quote(string)
    return uri
Пример #5
0
    def createInfMapJapan(self, df, date):
                
        if df is False:
            return
        
        # 空のグラフオブジェクトを作成
        fig = plt.figure(figsize=(self.graph_width_map, self.graph_hight_map),
                         facecolor=self.bgcolor_map, dpi=self.graph_dpi, 
                         tight_layout=True)
        
        # 都道府県名を行名に設定
        df_in = df.set_index("Pref")
        
        # カラーマップの作成
        cmap = plt.get_cmap('Blues')
        
        # 値の正規化
        norm = mpl.colors.Normalize(vmin=df_in["InfNum"].min(), vmax=df_in["InfNum"].max())
        
        # 色変換
        fcol = lambda x: '#' + bytes(cmap(norm(x), bytes=True)[:3]).hex()

        # カラーバーの作成
        mappable = plt.cm.ScalarMappable(norm, cmap)
        mappable.set_array(df_in["InfNum"])
        plt.colorbar(mappable)
        
        # タイトルの設定
        title = self.title_map + date
        plt.title(title)
        
        # 軸ラベル削除
        plt.tick_params(labelbottom=False, labelleft=False,
                        labelright=False, labeltop=False)
        
        # 軸メモリ削除
        plt.tick_params(bottom=False, left=False, right=False, top=False)
        
        # 描画
        plt.imshow(picture(df_in["InfNum"].apply(fcol)));     
        
        # 表示
#        plt.show()
        
        return fig
Пример #6
0
    def create_figure(self, mcmc_sample):
        r = mcmc_sample['r'].mean(axis=0)
        # print(r)
        df = pandas.DataFrame(r, columns=['r'])
        # print(df)
        cmap = plt.get_cmap('binary')
        norm = plt.Normalize(vmin=9.0, vmax=19.0)
        fcol = lambda x: '#' + bytes(cmap(norm(x), bytes=True)[:3]).hex()
        plt.colorbar(plt.cm.ScalarMappable(norm, cmap))
        plt.title('r')

        # indexを振り直す
        df = df['r'].apply(fcol)
        df.index = df.index + 1

        plt.imshow(picture(df))
        plt.show()
        plt.close()
Пример #7
0
    equal_to(sum_poly([q[i][c] for c in range(num_colors)]), 1)
    for i in range(num_region)
]

# 隣接する領域間の制約
adj_constraints = [
    # 都道府県コードと配列インデックスは1ずれてるので注意
    penalty(q[i][c] * q[j - 1][c]) for i in range(num_region)
    for j in jm.adjacent(i + 1)  # j: 隣接している都道府県コード
    if i + 1 < j for c in range(num_colors)
]

constraints = sum(reg_constraints) + sum(adj_constraints)

model = BinaryQuadraticModel(constraints)
result = solver.solve(model)
if len(result) == 0:
    raise RuntimeError("Any one of constraints is not satisfied.")

values = result[0].values
q_values = decode_solution(q, values, 1)

color_indices = np.where(np.array(q_values) == 1)[1]
color_map = {
    jm.pref_names[i + 1]: colors[color_indices[i]]
    for i in range(len(color_indices))
}

plt.rcParams["figure.figsize"] = 6, 6
plt.imshow(jm.picture(color_map))
plt.show()
Пример #8
0
        #              fmt='o', ecolor='gray', ms=10, alpha=0.8, marker='o', mfc='green', capsize=3)
        ax = plt.axes()
        ax.set_aspect('equal')
        plt.setp(ax, xlabel='Y', ylabel='r')
        plt.show()
        plt.close()


if __name__ == '__main__':
    m = Markov2Dim('data-map-temperature.txt', 'data-map-neighbor.txt',
                   '../model/model12-8')
    m.describe()

    # Figure of Japan map.
    plt.rcParams['figure.figsize'] = 6, 6
    plt.imshow(picture())
    plt.show()
    plt.close()

    m.create_figure_y()

    # モデリング
    stan_data = m.create_data()
    mcmc_sample = m.fit(stan_data)

    # モデリングした結果の可視化
    m.create_figure(mcmc_sample)

    # 予測と実測のプロット
    m.observe_diff_mean(mcmc_sample)
Пример #9
0
def get_svg(request, pk):
    # plt.rcParams['figure.figsize'] = 6, 6
    return plt.imshow(picture())
Пример #10
0
# Google Trends(トレンド)からデータ取得
pytrends = TrendReq(hl='ja-JP', tz=-540)

kw_list = [keyword]
pytrends.build_payload(kw_list, cat=0, timeframe='today 1-m', geo='JP', gprop='')

df = pytrends.interest_by_region(resolution='JP', inc_low_vol=True, inc_geo_code=True)
df['geoCode'] = df['geoCode'].str.replace('JP-', '').astype(int)

# データ作成
# 共通データ作成
cmap = plt.get_cmap('jet')
norm = plt.Normalize(vmin=df[keyword].min(), vmax=df[keyword].max())
# カラーバー用データを作成
mappable = cm.ScalarMappable(cmap=cmap, norm=norm)
mappable._A = []
# 日本地図用データを作成
fcol = lambda x: '#' + bytes(cmap(norm(x), bytes=True)[:3]).hex()

# 図を描画
# 図のベースを描く
plt.figure(figsize=(10, 8))
# 日本地図を描く
plt.imshow(picture(df[keyword].apply(fcol)));
# カラーバーを描く
plt.colorbar(mappable)

plt.savefig('{}.png'.format(keyword))
plt.show()