25 个常用 Matplotlib 图的 Python 代码(三)

简介: 大家好,今天要分享给大家25个Matplotlib图的汇总,在数据分析和可视化中非常有用,文章较长,可以马起来慢慢练手。

10. 发散型条形图

如果您想根据单个指标查看项目的变化情况,并可视化此差异的顺序和数量,那么发散条是一个很好的工具。它有助于快速区分数据中组的性能,并且非常直观,并且可以立即传达这一点。

# Prepare Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")

x = df.loc[:, ['mpg']]

df['mpg_z'] = (x - x.mean())/x.std()

df['colors'] = ['red'if x < 0else'green'for x in df['mpg_z']]

df.sort_values('mpg_z', inplace=True)

df.reset_index(inplace=True)


# Draw plot

plt.figure(figsize=(14,10), dpi= 80)

plt.hlines(y=df.index, xmin=0, xmax=df.mpg_z, color=df.colors, alpha=0.4, linewidth=5)


# Decorations

plt.gca().set(ylabel='$Model$', xlabel='$Mileage$')

plt.yticks(df.index, df.cars, fontsize=12)

plt.title('Diverging Bars of Car Mileage', fontdict={'size':20})

plt.grid(linestyle='--', alpha=0.5)

plt.show()

34.jpg

11. 发散型文本

分散的文本类似于发散条,如果你想以一种漂亮和可呈现的方式显示图表中每个项目的价值,它更喜欢。

# Prepare Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")

x = df.loc[:, ['mpg']]

df['mpg_z'] = (x - x.mean())/x.std()

df['colors'] = ['red'if x < 0else'green'for x in df['mpg_z']]

df.sort_values('mpg_z', inplace=True)

df.reset_index(inplace=True)


# Draw plot

plt.figure(figsize=(14,14), dpi= 80)

plt.hlines(y=df.index, xmin=0, xmax=df.mpg_z)

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 < 0else'left',

                verticalalignment='center', fontdict={'color':'red'if x < 0else'green', 'size':14})


# Decorations    

plt.yticks(df.index, df.cars, fontsize=12)

plt.title('Diverging Text Bars of Car Mileage', fontdict={'size':20})

plt.grid(linestyle='--', alpha=0.5)

plt.xlim(-2.5, 2.5)

plt.show()


35.jpg


12. 发散型包点图

发散点图也类似于发散条。然而,与发散条相比,条的不存在减少了组之间的对比度和差异。

# Prepare Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")

x = df.loc[:, ['mpg']]

df['mpg_z'] = (x - x.mean())/x.std()

df['colors'] = ['red'if x < 0else'darkgreen'for x in df['mpg_z']]

df.sort_values('mpg_z', inplace=True)

df.reset_index(inplace=True)


# Draw plot

plt.figure(figsize=(14,16), dpi= 80)

plt.scatter(df.mpg_z, df.index, s=450, alpha=.6, color=df.colors)

for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z):

   t = plt.text(x, y, round(tex, 1), horizontalalignment='center',

                verticalalignment='center', fontdict={'color':'white'})


# Decorations

# Lighten borders

plt.gca().spines["top"].set_alpha(.3)

plt.gca().spines["bottom"].set_alpha(.3)

plt.gca().spines["right"].set_alpha(.3)

plt.gca().spines["left"].set_alpha(.3)


plt.yticks(df.index, df.cars)

plt.title('Diverging Dotplot of Car Mileage', fontdict={'size':20})

plt.xlabel('$Mileage$')

plt.grid(linestyle='--', alpha=0.5)

plt.xlim(-2.5, 2.5)

plt.show()

36.jpg


13. 带标记的发散型棒棒糖图

带标记的棒棒糖通过强调您想要引起注意的任何重要数据点并在图表中适当地给出推理,提供了一种可视化分歧的灵活方式。

# Prepare Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")

x = df.loc[:, ['mpg']]

df['mpg_z'] = (x - x.mean())/x.std()

df['colors'] = 'black'


# color fiat differently

df.loc[df.cars == 'Fiat X1-9', 'colors'] = 'darkorange'

df.sort_values('mpg_z', inplace=True)

df.reset_index(inplace=True)



# Draw plot

import matplotlib.patches as patches


plt.figure(figsize=(14,16), dpi= 80)

plt.hlines(y=df.index, xmin=0, xmax=df.mpg_z, color=df.colors, alpha=0.4, linewidth=1)

plt.scatter(df.mpg_z, df.index, color=df.colors, s=[600if x == 'Fiat X1-9'else300for x in df.cars], alpha=0.6)

plt.yticks(df.index, df.cars)

plt.xticks(fontsize=12)


# Annotate

plt.annotate('Mercedes Models', xy=(0.0, 11.0), xytext=(1.0, 11), xycoords='data',

           fontsize=15, ha='center', va='center',

           bbox=dict(boxstyle='square', fc='firebrick'),

           arrowprops=dict(arrowstyle='-[, widthB=2.0, lengthB=1.5', lw=2.0, color='steelblue'), color='white')


# Add Patches

p1 = patches.Rectangle((-2.0, -1), width=.3, height=3, alpha=.2, facecolor='red')

p2 = patches.Rectangle((1.5, 27), width=.8, height=5, alpha=.2, facecolor='green')

plt.gca().add_patch(p1)

plt.gca().add_patch(p2)


# Decorate

plt.title('Diverging Bars of Car Mileage', fontdict={'size':20})

plt.grid(linestyle='--', alpha=0.5)

plt.show()

37.jpg

14.面积图

通过对轴和线之间的区域进行着色,区域图不仅强调峰值和低谷,而且还强调高点和低点的持续时间。高点持续时间越长,线下面积越大。

import numpy as np

import pandas as pd


# Prepare Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv", parse_dates=['date']).head(100)

x = np.arange(df.shape[0])

y_returns = (df.psavert.diff().fillna(0)/df.psavert.shift(1)).fillna(0) * 100


# Plot

plt.figure(figsize=(16,10), dpi= 80)

plt.fill_between(x[1:], y_returns[1:], 0, where=y_returns[1:] >= 0, facecolor='green', interpolate=True, alpha=0.7)

plt.fill_between(x[1:], y_returns[1:], 0, where=y_returns[1:] <= 0, facecolor='red', interpolate=True, alpha=0.7)


# Annotate

plt.annotate('Peak
1975'
, xy=(94.0, 21.0), xytext=(88.0, 28),

            bbox=dict(boxstyle='square', fc='firebrick'),

            arrowprops=dict(facecolor='steelblue', shrink=0.05), fontsize=15, color='white')



# Decorations

xtickvals = [str(m)[:3].upper()+"-"+str(y) for y,m in zip(df.date.dt.year, df.date.dt.month_name())]

plt.gca().set_xticks(x[::6])

plt.gca().set_xticklabels(xtickvals[::6], rotation=90, fontdict={'horizontalalignment': 'center', 'verticalalignment': 'center_baseline'})

plt.ylim(-35,35)

plt.xlim(1,100)

plt.title("Month Economics Return %", fontsize=22)

plt.ylabel('Monthly returns %')

plt.grid(alpha=0.5)

plt.show()


38.jpg

15. 有序条形图

有序条形图有效地传达了项目的排名顺序。但是,在图表上方添加度量标准的值,用户可以从图表本身获取精确信息。

# Prepare Data

df_raw = pd.read_csv("https://github.com/selva86/datasets/raw/master/mpg_ggplot2.csv")

df = df_raw[['cty', 'manufacturer']].groupby('manufacturer').apply(lambda x: x.mean())

df.sort_values('cty', inplace=True)

df.reset_index(inplace=True)


# Draw plot

import matplotlib.patches as patches


fig, ax = plt.subplots(figsize=(16,10), facecolor='white', dpi= 80)

ax.vlines(x=df.index, ymin=0, ymax=df.cty, color='firebrick', alpha=0.7, linewidth=20)


# Annotate Text

for i, cty in enumerate(df.cty):

   ax.text(i, cty+0.5, round(cty, 1), horizontalalignment='center')



# Title, Label, Ticks and Ylim

ax.set_title('Bar Chart for Highway Mileage', fontdict={'size':22})

ax.set(ylabel='Miles Per Gallon', ylim=(0, 30))

plt.xticks(df.index, df.manufacturer.str.upper(), rotation=60, horizontalalignment='right', fontsize=12)


# Add patches to color the X axis labels

p1 = patches.Rectangle((.57, -0.005), width=.33, height=.13, alpha=.1, facecolor='green', transform=fig.transFigure)

p2 = patches.Rectangle((.124, -0.005), width=.446, height=.13, alpha=.1, facecolor='red', transform=fig.transFigure)

fig.add_artist(p1)

fig.add_artist(p2)

plt.show()


39.jpg




相关文章
|
2月前
|
存储 算法 调度
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
176 26
|
2月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
305 1
|
2月前
|
机器学习/深度学习 算法 调度
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
159 1
|
1月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
232 100
|
1月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
334 95
|
2月前
|
Python
Python的简洁之道:5个让代码更优雅的技巧
Python的简洁之道:5个让代码更优雅的技巧
228 104
|
2月前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
421 99
|
1月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
149 88
|
2月前
|
IDE 开发工具 开发者
Python类型注解:提升代码可读性与健壮性
Python类型注解:提升代码可读性与健壮性
257 102
|
1月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。