python可视化学习十一(发散型文本图)

import numpy as np
import importlib as mpl
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

在这里插入图片描述

#数据的准备
df =pd.read_csv('mtcars.csv')
x=df.loc[:,['mpg']]#提取想要的数据
df['mpg_z']=(x-x.mean())/x.std() #标准化的处理
df['color']=['red' if x<0 else 'green' for x in df['mpg_z']] #生成颜色的标签列
df.sort_values('mpg_z',inplace=True)
df.reset_index(inplace=True,drop=True)
#简单的绘制
plt.figure(figsize=(12,10),dpi=63)
#绘制基本的图像
plt.hlines(y=df.cars,xmin=0,xmax=df.mpg_z)
#添加文本

for i in range(df.shape[0]): #对每一个数据进行循坏
    x=df.mpg_z[i]           #获取每一个 x的值
    y=df.index[i]          #获取每一的y的值
    s=str(round(df.mpg_z[i],2)) #四舍五入保留2位小数
    plt.text(x,y,s,color=df.color[i])#绘制简单的文本图

在这里插入图片描述
在这里插入图片描述

#简单的绘制
plt.figure(figsize=(12,10),dpi=63)
#绘制基本的图像
plt.hlines(y=df.cars,xmin=0, xmax=df.mpg_z,alpha=0.5,linewidth=5)
#添加文本
for i in range(df.shape[0]): #对每一个数据进行循坏
    x=df.mpg_z[i]           #获取每一个 x的值
    y=df.index[i]          #获取每一的y的值
    s=str(round(df.mpg_z[i],2)) #四舍五入保留2位小数
    plt.text(x,y,s,
            fontdict={'color':df.color[i],'size':12} #此处添加颜色与尺寸,以字典的形式打包
            ,horizontalalignment='right'if x<0 else 'left'#水平对齐参数,有left,right ,center三种选择,文本的那一边与位置的对齐
            ,verticalalignment ='center'                        #垂直对齐参数,常用的有bottom,top,center
            )#绘制简单的文本图  

#添加装饰

plt.gca().set(ylabel='$Model$', xlabel='$Mileage$')
plt.yticks(df.index, df.cars, fontsize=15)
plt.title('Diverging Bars of Car Mileage', fontdict={'size':20})
plt.grid(linestyle='--', alpha=1)
plt.show()  

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值