溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何用Python來仿制一張R語言的數(shù)據(jù)可視化圖

發(fā)布時(shí)間:2021-11-22 14:56:26 來源:億速云 閱讀:123 作者:柒染 欄目:大數(shù)據(jù)

如何用Python來仿制一張R語言的數(shù)據(jù)可視化圖,針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

簡介

開門見山,今天我們要模仿的數(shù)據(jù)可視化作品來自 「#TidyTuesday」 活動(dòng)于2020年1月28日發(fā)布的「舊金山街道樹木數(shù)據(jù)集」下的眾多參賽作品中,由Philippe Massicotte創(chuàng)作的(如圖1所示)非常受歡迎的 「Street trees of San Francisco」

如何用Python來仿制一張R語言的數(shù)據(jù)可視化圖

而路網(wǎng)數(shù)據(jù)我們則可以利用osmnx進(jìn)行在線獲取,只需傳入我們的舊金山面數(shù)據(jù)bbox范圍,配合

osmnx進(jìn)行獲取即可:

接著我們在上述數(shù)據(jù)基礎(chǔ)上對每個(gè)社區(qū)面內(nèi)部的街道樹木數(shù)量進(jìn)行統(tǒng)計(jì)并對數(shù)據(jù)進(jìn)行分箱,配上預(yù)設(shè)區(qū)間的色彩值:

# 統(tǒng)計(jì)每個(gè)社區(qū)內(nèi)部的樹木數(shù)量
sf_trees = \
(
    gpd
    # 空間連接
    .sjoin(left_df=sf,
           right_df=trees,
           op='contains',
           how='left')
    # 按照name分組計(jì)數(shù)(這里未連接到任何數(shù)的社區(qū)被
    # 記為1本質(zhì)上是錯(cuò)誤的,但我們繪圖分段后這一點(diǎn)不影響)
    .groupby('name')
    .agg({
        'name': 'count',
        'geometry': 'first'
    })
    .rename(columns={'name': '數(shù)量'})
    .reset_index(drop=False)
    # 直接轉(zhuǎn)為GeoDataFrame
    .pipe(gpd.GeoDataFrame, crs='EPSG:4326')
)

sf_trees['顏色'] = (
    pd
    .cut(sf_trees['數(shù)量'], 
         bins=[0, 2500, 5000, 7500, 10000, max(sf_trees['數(shù)量'])], 
         labels=['#e4f1e1', '#c0dfd1', '#67a9a2', '#3b8383', '#145e64'])
)

最后別忘記了我們作為輪廓的緩沖區(qū)生成:

# 生成輪廓緩沖區(qū)
sf_bounds = gpd.GeoSeries([sf.buffer(0.001).unary_union], crs='EPSG:4326')

「主要視覺元素繪制」

做好這些準(zhǔn)備后我們直接就可以先將圖像的主體元素繪制出來:

import matplotlib.pyplot as plt
from matplotlib import font_manager as fm

# 設(shè)置全局默認(rèn)字體
plt.rcParams['font.sans-serif'] = ['Times New Roman']

fig, ax = plt.subplots(figsize=(6, 6))

# 設(shè)置背景色
ax.set_facecolor('#333333')
fig.set_facecolor('#333333')

# 圖層1:緩沖區(qū)輪廓
ax = (
    sf_bounds
    .plot(ax=ax, facecolor='none', edgecolor='#cccccc', linewidth=1)
)

# 圖層2:帶有樹木統(tǒng)計(jì)信息的社區(qū)面
ax = (
    sf_trees
    .plot(color=sf_trees['顏色'], edgecolor='#333333',
          linewidth=0.5, ax=ax)
)

# 圖層3:osm路網(wǎng)
ax = (
    roads
    .plot(linewidth=0.05, edgecolor='#3c3d3d',
          ax=ax)
)

# 設(shè)置x軸
ax.set_xticks([-122.5, -122.45, -122.4, -122.35])
ax.set_xticklabels(['122.5°W', '122.45°W', '122.4°W', '122.35°W'])

# 設(shè)置y軸
ax.set_yticks([37.72, 37.74, 37.76, 37.78, 37.8, 37.82])
ax.set_yticklabels(['37.72°N', '37.74°N', '37.76°N', '37.78°N', '37.8°N', '37.82°N'])

# 設(shè)置坐標(biāo)軸樣式
ax.tick_params(axis='both', labelcolor='#737373', color='none', labelsize=8)

# 隱藏周圍的spines線條
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')

# 導(dǎo)出圖像
fig.savefig('圖4.png', dpi=600, bbox_inches='tight')

如何用Python來仿制一張R語言的數(shù)據(jù)可視化圖

「輔助視覺元素的添加」

接下來我們只需要補(bǔ)充上各種點(diǎn)睛之筆的小元素即可,其中值得一提的是下方的圖例我們用inset_axes()插入子圖的方式靈活實(shí)現(xiàn)。

并且外部字體文件的使用也是很添彩的,我們這里就分別在「標(biāo)題」「刻度標(biāo)簽」處使用到了兩種特殊的字體(你可以在開頭的Github倉庫找到我用到的所有字體文件):

fig, ax = plt.subplots(figsize=(6, 6))

# 設(shè)置背景色
ax.set_facecolor('#333333')
fig.set_facecolor('#333333')

# 圖層1:緩沖區(qū)輪廓
ax = (
    sf_bounds
    .plot(ax=ax, facecolor='none', edgecolor='#cccccc', linewidth=1)
)

# 圖層2:帶有樹木統(tǒng)計(jì)信息的社區(qū)面
ax = (
    sf_trees
    .plot(color=sf_trees['顏色'], edgecolor='#333333',
          linewidth=0.5, ax=ax)
)

# 圖層3:osm路網(wǎng)
ax = (
    roads
    .plot(linewidth=0.05, edgecolor='#3c3d3d',
          ax=ax)
)

# 設(shè)置x軸
ax.set_xticks([-122.5, -122.45, -122.4, -122.35])
ax.set_xticklabels(['122.5°W', '122.45°W', '122.4°W', '122.35°W'])

# 設(shè)置y軸
ax.set_yticks([37.72, 37.74, 37.76, 37.78, 37.8, 37.82])
ax.set_yticklabels(['37.72°N', '37.74°N', '37.76°N', '37.78°N', '37.8°N', '37.82°N'])

# 設(shè)置坐標(biāo)軸樣式
ax.tick_params(axis='both', labelcolor='#737373', color='none', labelsize=8)

# 隱藏周圍的spines線條
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')

# 以插入子圖的方式添加下方圖例
ax_bar = ax.inset_axes((0.25, -0.12, 0.5, 0.015))
ax_bar.set_facecolor('#333333')
ax_bar.spines['left'].set_color('none')
ax_bar.spines['right'].set_color('none')
ax_bar.spines['top'].set_color('none')
ax_bar.spines['bottom'].set_color('none')

ax_bar.bar(range(5), [1]*5, width=0.975, color=['#e4f1e1', '#c0dfd1', '#67a9a2', '#3b8383', '#145e64'])
ax_bar.set_yticks([])
ax_bar.set_xticks([i+0.5 for i in range(4)])
ax_bar.set_xticklabels(['2500', '5000', '7500', '10000'], 
                       fontdict={'fontproperties': fm.FontProperties(fname="RobotoCondensed-Regular.ttf")})
ax_bar.tick_params(color='none', labelcolor='#ffffff', labelsize=8, pad=0)

ax.set_title('Street trees of San Francisco', 
             fontsize=24,
             color='#ffffff',
             pad=40,
             fontproperties=fm.FontProperties(fname="Amaranth-Bold.ttf"))

ax.text(0.5, 1.08, '''There are a total of 192987 trees in San Francisco regrouped into 571 species.
The district with the most number of trees is Mission whereas the one with
the least number of trees is LincoLn Park / Ft. Miley.''', transform=ax.transAxes, ma='center',
        ha='center', va='top', color='#ffffff')

ax.text(0.5, -0.22, 'Visualization by CNFeffery', fontsize=8,
        color='#737373', ha='center', transform=ax.transAxes)

# 導(dǎo)出圖像
fig.savefig('圖5.png', dpi=600, bbox_inches='tight')

關(guān)于如何用Python來仿制一張R語言的數(shù)據(jù)可視化圖問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI