網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
python繪制發(fā)散型柱狀圖+誤差陰影時(shí)間序列圖+雙坐標(biāo)系時(shí)間序列圖+繪制金字塔圖_python
作者:不再依然07 ? 更新時(shí)間: 2022-10-12 編程語(yǔ)言1.繪制發(fā)散型柱狀圖
python繪制發(fā)散型柱狀圖,展示單個(gè)指標(biāo)的變化的順序和數(shù)量,在柱子上添加了數(shù)值文本。
實(shí)現(xiàn)代碼:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings(action='once')
df = pd.read_csv("C:\工作\學(xué)習(xí)\數(shù)據(jù)雜壇/datasets/mtcars.csv")
x = df.loc[:, ['mpg']]
df['mpg_z'] = (x - x.mean()) / x.std()
df['colors'] = ['red' if x < 0 else 'green' for x in df['mpg_z']]
df.sort_values('mpg_z', inplace=True)
df.reset_index(inplace=True)
# Draw plot
plt.figure(figsize=(10, 6), dpi=80)
plt.hlines(y=df.index,
? ? ? ? ? ?xmin=0,
? ? ? ? ? ?xmax=df.mpg_z,
? ? ? ? ? ?color=df.colors,
? ? ? ? ? ?alpha=0.8,
? ? ? ? ? ?linewidth=5)
for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z):
? ? t = plt.text(x, y, round(tex, 2), horizontalalignment='right' if x < 0 else 'left',
? ? ? ? ? ? ? ? ?verticalalignment='center', fontdict={'color':'black' if x < 0 else 'black', 'size':10})
# Decorations
plt.gca().set(ylabel='$Model', xlabel='$Mileage')
plt.yticks(df.index, df.cars, fontsize=12)
plt.xticks(fontsize=12)
plt.title('Diverging Bars of Car Mileage')
plt.grid(linestyle='--', alpha=0.5)
plt.show()
實(shí)現(xiàn)效果:
2.繪制帶誤差陰影的時(shí)間序列圖
實(shí)現(xiàn)功能:
python繪制帶誤差陰影的時(shí)間序列圖。
實(shí)現(xiàn)代碼:
from scipy.stats import sem
import pandas as pd
import matplotlib.pyplot as plt
# Import Data
df_raw = pd.read_csv('F:\數(shù)據(jù)雜壇\datasets\orders_45d.csv',
? ? ? ? ? ? ? ? ? ? ?parse_dates=['purchase_time', 'purchase_date'])
# Prepare Data: Daily Mean and SE Bands
df_mean = df_raw.groupby('purchase_date').quantity.mean()
df_se = df_raw.groupby('purchase_date').quantity.apply(sem).mul(1.96)
# Plot
plt.figure(figsize=(10, 6), dpi=80)
plt.ylabel("Daily Orders", fontsize=12)
x = [d.date().strftime('%Y-%m-%d') for d in df_mean.index]
plt.plot(x, df_mean, color="#c72e29", lw=2)
plt.fill_between(x, df_mean - df_se, df_mean + df_se, color="#f8f2e4")
# Decorations
# Lighten borders
plt.gca().spines["top"].set_alpha(0)
plt.gca().spines["bottom"].set_alpha(1)
plt.gca().spines["right"].set_alpha(0)
plt.gca().spines["left"].set_alpha(1)
plt.xticks(x[::6], [str(d) for d in x[::6]], fontsize=12)
plt.title("Daily Order Quantity of Brazilian Retail with Error Bands (95% confidence)",fontsize=14)
# Axis limits
s, e = plt.gca().get_xlim()
plt.xlim(s, e - 2)
plt.ylim(4, 10)
# Draw Horizontal Tick lines
for y in range(5, 10, 1):
? ? plt.hlines(y,
? ? ? ? ? ? ? ?xmin=s,
? ? ? ? ? ? ? ?xmax=e,
? ? ? ? ? ? ? ?colors='black',
? ? ? ? ? ? ? ?alpha=0.5,
? ? ? ? ? ? ? ?linestyles="--",
? ? ? ? ? ? ? ?lw=0.5)
plt.show()
實(shí)現(xiàn)效果:
3.繪制雙坐標(biāo)系時(shí)間序列圖
實(shí)現(xiàn)功能:
python繪制雙坐標(biāo)系(雙變量)時(shí)間序列圖。
實(shí)現(xiàn)代碼:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Import Data
df = pd.read_csv("F:\數(shù)據(jù)雜壇\datasets\economics.csv")
x = df['date']
y1 = df['psavert']
y2 = df['unemploy']
# Plot Line1 (Left Y Axis)
fig, ax1 = plt.subplots(1, 1, figsize=(12, 6), dpi=100)
ax1.plot(x, y1, color='tab:red')
# Plot Line2 (Right Y Axis)
ax2 = ax1.twinx() ?# instantiate a second axes that shares the same x-axis
ax2.plot(x, y2, color='tab:blue')
# Decorations
# ax1 (left Y axis)
ax1.set_xlabel('Year', fontsize=18)
ax1.tick_params(axis='x', rotation=70, labelsize=12)
ax1.set_ylabel('Personal Savings Rate', color='#dc2624', fontsize=16)
ax1.tick_params(axis='y', rotation=0, labelcolor='#dc2624')
ax1.grid(alpha=.4)
# ax2 (right Y axis)
ax2.set_ylabel("Unemployed (1000's)", color='#01a2d9', fontsize=16)
ax2.tick_params(axis='y', labelcolor='#01a2d9')
ax2.set_xticks(np.arange(0, len(x), 60))
ax2.set_xticklabels(x [::60], rotation=90, fontdict={'fontsize': 10})
ax2.set_title(
? ? "Personal Savings Rate vs Unemployed: Plotting in Secondary Y Axis",
? ? fontsize=18)
fig.tight_layout()
plt.show()
實(shí)現(xiàn)效果:
4.繪制金字塔圖
實(shí)現(xiàn)功能:
python繪制金字塔圖,一種排過(guò)序的分組水平柱狀圖barplot,可很好展示不同分組之間的差異,可可視化逐級(jí)過(guò)濾或者漏斗的每個(gè)階段。
實(shí)現(xiàn)代碼:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Read data
df = pd.read_csv("D:\數(shù)據(jù)雜壇\datasets\email_campaign_funnel.csv")
# Draw Plot
plt.figure()
group_col = 'Gender'
order_of_bars = df.Stage.unique()[::-1]
colors = [
? ? plt.cm.Set1(i / float(len(df[group_col].unique()) - 1))
? ? for i in range(len(df[group_col].unique()))
]
for c, group in zip(colors, df[group_col].unique()):
? ? sns.barplot(x='Users',
? ? ? ? ? ? ? ? y='Stage',
? ? ? ? ? ? ? ? data=df.loc[df[group_col] == group, :],
? ? ? ? ? ? ? ? order=order_of_bars,
? ? ? ? ? ? ? ? color=c,
? ? ? ? ? ? ? ? label=group)
# Decorations
plt.xlabel("$Users$")
plt.ylabel("Stage of Purchase")
plt.yticks(fontsize=12)
plt.title("Population Pyramid of the Marketing Funnel", fontsize=18)
plt.legend()
plt.savefig('C:\工作\學(xué)習(xí)\數(shù)據(jù)雜壇\素材\\0815\金字塔', dpi=300, bbox_inches = 'tight')
plt.show()
實(shí)現(xiàn)效果:
原文鏈接:https://blog.csdn.net/sinat_41858359/article/details/125996714
相關(guān)推薦
- 2022-09-08 pandas時(shí)間序列之如何將int轉(zhuǎn)換成datetime格式_python
- 2022-10-22 Oracle根據(jù)時(shí)間查詢的一些常見(jiàn)情況匯總_oracle
- 2022-07-20 使用numpy.ndarray添加元素_python
- 2022-04-04 快應(yīng)用開(kāi)發(fā)自定義事件 快應(yīng)用層級(jí) 圖片對(duì)象Image 獲取元素的寬高
- 2022-05-20 python繪制餅圖的方法詳解_python
- 2022-09-23 React深入了解原理_React
- 2023-04-26 C語(yǔ)言實(shí)現(xiàn)數(shù)組元素排序方法詳解_C 語(yǔ)言
- 2022-07-02 css文字顯示兩行,溢出顯示省略號(hào),點(diǎn)擊查看更多
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支