脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图

python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图

2022-08-16 20:33不再依然07 Python

这篇文章主要介绍了python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图,详细的内容需要的小伙伴可以参考一下下面文章内容

1.绘制发散型柱状图

python绘制发散型柱状图,展示单个指标的变化的顺序和数量,在柱子上添加了数值文本。

实现代码:

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:工作学习数据杂坛/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()

实现效果:

python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图

 

2.绘制带误差阴影的时间序列图

实现功能:

python绘制带误差阴影的时间序列图。

实现代码:

from scipy.stats import sem
import pandas as pd
import matplotlib.pyplot as plt
# Import Data
df_raw = pd.read_csv("F:数据杂坛datasetsorders_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()

实现效果:

python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图

 

3.绘制双坐标系时间序列图

实现功能:

python绘制双坐标系(双变量)时间序列图。

实现代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Import Data
df = pd.read_csv("F:数据杂坛datasetseconomics.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()

实现效果:

python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图

 

4.绘制金字塔图

实现功能:

python绘制金字塔图,一种排过序的分组水平柱状图barplot,可很好展示不同分组之间的差异,可可视化逐级过滤或者漏斗的每个阶段。

实现代码:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Read data
df = pd.read_csv("D:数据杂坛datasetsemail_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:工作学习数据杂坛素材815金字塔", dpi=300, bbox_inches = "tight")
plt.show()

实现效果:

python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图

到此这篇关于python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图的文章就介绍到这了,更多相关Python图绘制内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.csdn.net/sinat_41858359/article/details/125996714

延伸 · 阅读

精彩推荐
  • PythonDjango中如何使用celery异步发送短信验证码详解

    Django中如何使用celery异步发送短信验证码详解

    Celery是Python开发的分布式任务调度模块,这篇文章主要给大家介绍了关于Django中如何使用celery异步发送短信验证码的相关资料,主要内容包括基础介绍、工作...

    一只阿龙6872021-12-30
  • PythonPython解析并读取PDF文件内容的方法

    Python解析并读取PDF文件内容的方法

    这篇文章主要介绍了Python解析并读取PDF文件内容的方法,结合实例形式分别描述了Python2.7在win32与win64环境下实现读取pdf的相关操作技巧,需要的朋友可以参考...

    开心果汁39162021-02-19
  • Pythonpython读取和保存mat文件的方法

    python读取和保存mat文件的方法

    本文主要介绍了python读取和保存mat文件的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    zhiyong_will6882021-12-24
  • PythonPython中MySQL数据迁移到MongoDB脚本的方法

    Python中MySQL数据迁移到MongoDB脚本的方法

    MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。本文给大家介绍Python中MySQL数据迁移到Mo...

    韩德田7462020-08-21
  • Pythonpython实现带错误处理功能的远程文件读取方法

    python实现带错误处理功能的远程文件读取方法

    这篇文章主要介绍了python实现带错误处理功能的远程文件读取方法,涉及Python使用socket操作远程文件的相关技巧,非常具有实用价值,需要的朋友可以参考下...

    重负在身3282020-06-17
  • Pythonpython学习之编写查询ip程序

    python学习之编写查询ip程序

    这篇文章主要介绍了python学习之编写查询ip程序 ,需要的朋友可以参考下 ...

    运维人生5162020-08-14
  • PythonPython利用matplotlib.pyplot.boxplot()绘制箱型图实例代码

    Python利用matplotlib.pyplot.boxplot()绘制箱型图实例代码

    相信大家应该都知道Python绘制箱线图主要用matplotlib库里pyplot模块里的boxplot()函数,下面这篇文章主要给大家介绍了关于Python利用matplotlib.pyplot.boxplot()绘制箱...

    小羊快学3922022-08-01
  • Pythonpython中的import语句用法大全

    python中的import语句用法大全

    import语句用来导入其他python文件(称为模块module),使用该模块里定义的类、方法或者变量,从而达到代码复用的目的,文中给大家提到import 语句的两种格...

    软件技术学习开发爱好者9562021-12-10