Python可视化 | 风玫瑰图可视化示例

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理

本篇文章来自腾讯云 作者:郭好奇同学
Python可视化 | 风玫瑰图可视化示例_第1张图片

https://github.com/python-windrose/windrose
pip install windrose
pip install git+https://github.com/python-windrose/windrose
git clone https://github.com/python-windrose/windrose
python setup.py install
from windrose import WindroseAxes
from matplotlib import pyplot as plt
import matplotlib.cm as cm
import numpy as np
# Create wind speed and direction variables
ws = np.random.random(500) * 6
wd = np.random.random(500) * 360

Python可视化 | 风玫瑰图可视化示例_第2张图片
Python可视化 | 风玫瑰图可视化示例_第3张图片

# 導入包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#-------設置支持中文----------------------#
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']   #設置簡黑字體
mpl.rcParams['axes.unicode_minus'] = False
#-------自定義座標軸刻度格式----------------#
from matplotlib.ticker import FuncFormatter
np.random.seed(0)
data = pd.DataFrame(np.random.randint(20, 300, (4, 16)), 
                    index=['0~0.2', '0.3~1.5', '1.6~3.3', '3.4~5.4'],
                    columns='N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW'.split())
_sum = data.apply(np.sum)
data = data / _sum
data
N = 16 # 風速分佈爲16個方向
theta = np.linspace(0, 2*np.pi, N, endpoint=False) # 獲取16個方向的角度值
width = np.pi / N  # 繪製扇型的寬度,可以自行調整
labels = list(data.columns) # 自定義座標標籤爲 N , NSN, ……
# 開始繪圖
plt.figure(figsize=(8,8))
ax = plt.subplot(111, projection='polar')
for idx in data.index:
    # 每一行繪製一個扇形
    radii = data.loc[idx] # 每一行數據
    ax.bar(theta, radii, width=width, bottom=0.0, label=idx, tick_label=labels)
#------------------------------------#
ax.set_theta_zero_location('N') #設置零度方向北
ax.set_theta_direction(-1)    # 逆時針方向繪圖
#--------自定義yaxis的刻度格式-----------#
plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda s, position: '{:.0f}%'.format(100*s)))
plt.title('風玫瑰圖示意圖')
plt.legend(loc=4, bbox_to_anchor=(1.15, -0.07)) # 將label顯示出來, 並調整位置
plt.savefig('F:/Rpython/lp15/plot6.4.png',dpi=600)
plt.show()

Python可视化 | 风玫瑰图可视化示例_第4张图片

'''
###### author:CynthiaLee & Masterpiece
'''
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from IPython.core.pylabtools import figsize
plt.rcParams['savefig.dpi'] = 600
plt.rcParams['figure.dpi'] = 600
file = r'F:/Rpython/lp15/pollutionrose2.xlsx'
data = pd.read_excel(file, usecols=['DATE', 'WD', 'WS', 'PM2.5'], index_col=0).iloc[:72, :]
data
data['WD'] = np.radians(data['WD'])
v = data['WS']
speed = np.linspace(v.min(), v.max(), endpoint=True, num=16)
deg = np.linspace(0, 2*np.pi, endpoint=True, num=32)
def maker(s, sequence):
     for i, val in enumerate(sequence):
        if s <= sequence[i+1]:
            return val
d = data['WD']
data['WS'] = v.apply(maker, sequence=speed)
data['WD'] = d.apply(maker, sequence=deg)
data.head()
data['PM2.5'] = data['PM2.5'].astype(float)
dt = data.pivot_table(values='PM2.5', index='WS', columns='WD', aggfunc=np.mean)
dt.fillna(0, inplace=True)
dt = dt.reindex(index=speed, columns=deg, fill_value=0)
dt.head(6)
theta, r = np.meshgrid(deg, speed)
fig,axl = plt.subplots(1,2, subplot_kw={'projection':'polar'},figsize=(9,5))
ax=axl[0]
ax.set_theta_zero_location("N")
ax.set_theta_direction('clockwise')
pos = ax.contourf(theta, r, dt.to_numpy(), cmap='RdBu_r')
cb = plt.colorbar(pos, ax=ax,pad=0.1)
ax.set_xticks([(i/4)*np.pi for i in range(8)])
ax.set_xticklabels(['N','NE','E','SE','S','SW','W','NW'],fontdict={'weight':'bold','size':15,'color':'b'})
ax.set_rmax(3)
ax.set_rticks([])
ax.set_title(r"PM2.5 $\mu g \cdot m^{-3}$",size=13, va='bottom',pad=20)
ax=axl[1]
ax.set_theta_zero_location("N")
ax.set_theta_direction('clockwise')
pos = ax.contourf(theta, r, dt.to_numpy(), cmap='jet')
cb = plt.colorbar(pos, ax=ax,pad=0.1)
ax.set_xticks([(i/4)*np.pi for i in range(8)])
ax.set_xticklabels(['北','东北','东','东南','南','西南','西','西北'],fontdict={'family':'SimHei','size':15,'color':'red'})
ax.set_rmax(3)
ax.set_rticks([])
ax.set_title(r"Article style: PM2.5 $\rm \mu g \cdot m^{-3}$",size=13, va='bottom',pad=20)
plt.savefig('F:/Rpython/lp15/plot5.png',dpi=600)
plt.show()# show the graph on screen

Python可视化 | 风玫瑰图可视化示例_第5张图片

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.core.pylabtools import figsize
from matplotlib.colors import ListedColormap
plt.rcParams['savefig.dpi'] = 600
plt.rcParams['figure.dpi'] = 600
file = r'F:/Rpython/lp15/pollutionrose2.xlsx'
data = pd.read_excel(file, usecols=['DATE', 'WD', 'WS', 'PM2.5'], index_col=0).iloc[:72, :]
data
data['WD'] = np.radians(data['WD'])
v = data['WS']
speed = np.linspace(v.min(), v.max(), endpoint=True, num=16)
deg = np.linspace(0, 2*np.pi, endpoint=True, num=32)
def maker(s, sequence):
     for i, val in enumerate(sequence):
        if s <= sequence[i+1]:
            return val
d = data['WD']
data['WS'] = v.apply(maker, sequence=speed)
data['WD'] = d.apply(maker, sequence=deg)
data.head()
data['PM2.5'] = data['PM2.5'].astype(float)
dt = data.pivot_table(values='PM2.5', index='WS', columns='WD', aggfunc=np.mean)
dt.fillna(0, inplace=True)
dt = dt.reindex(index=speed, columns=deg, fill_value=0)
dt.head(6)
theta, r = np.meshgrid(deg, speed)
#fig, ax = plt.subplots(projection='polar')
ax = plt.subplot(projection='polar')
ax.set_theta_zero_location("N")
ax.set_theta_direction('clockwise')
#读取.rgb文件
rgb = pd.read_csv('F:/Rpython/lp12/colormaps/3gauss.rgb',sep='\s+',skiprows=2,names=['r','g','b']).values/255
#将rgb信息映射为colormap
colormap = ListedColormap(rgb)
pos = ax.contourf(theta, r, dt.to_numpy(), cmap=colormap)
cb = plt.colorbar(pos, ax=ax,pad=0.1)
cb.set_label("PM2.5 μg⋅m^(-3)",size=8)
cb.ax.tick_params(labelsize=8)
plt.title("King's Park(0716-0718)",y=1,size=10)
plt.savefig('F:/Rpython/lp15/plot2.png',dpi=600)
plt.show()# show the graph on screen

Python可视化 | 风玫瑰图可视化示例_第6张图片

你可能感兴趣的:(python,python,可视化)