实现功能:
python绘制发散型柱状图,展示单个指标的变化的顺序和数量,在柱子上添加了数值文本。
实现代码:
1 | import numpy as np |
2 | import pandas as pd |
3 | import matplotlib as mpl |
4 | import matplotlib.pyplot as plt |
5 | import seaborn as sns |
6 | import warnings |
7 | warnings.filterwarnings(action='once') |
8 | |
9 | df = pd.read_csv("C:\工作\学习\数据杂坛/datasets/mtcars.csv") |
10 | x = df.loc[:, ['mpg']] |
11 | df['mpg_z'] = (x - x.mean()) / x.std() |
12 | df['colors'] = ['red' if x < 0 else 'green' for x in df['mpg_z']] |
13 | df.sort_values('mpg_z', inplace=True) |
14 | df.reset_index(inplace=True) |
15 | |
16 | # Draw plot |
17 | plt.figure(figsize=(10, 6), dpi=80) |
18 | plt.hlines(y=df.index, |
19 | xmin=0, |
20 | xmax=df.mpg_z, |
21 | color=df.colors, |
22 | alpha=0.8, |
23 | linewidth=5) |
24 | |
25 | for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z): |
26 | t = plt.text(x, y, round(tex, 2), horizontalalignment='right' if x < 0 else 'left', |
27 | verticalalignment='center', fontdict={'color':'black' if x < 0 else 'black', 'size':10}) |
28 | |
29 | # Decorations |
30 | plt.gca().set(ylabel='$Model', xlabel='$Mileage') |
31 | plt.yticks(df.index, df.cars, fontsize=12) |
32 | plt.xticks(fontsize=12) |
33 | plt.title('Diverging Bars of Car Mileage') |
34 | plt.grid(linestyle='--', alpha=0.5) |
35 | plt.show() |
实现效果:
喜欢记得点赞,在看,收藏,
关注V订阅号:数据杂坛,获取数据集,完整代码和效果,将持续更新!
留言与评论(共有 0 条评论) “” |