Python绘制频率分布直方图和条形图

我们平时做数据分析的时候,经常要了解数据的分布情况,这时候就需要画出频率分布直方图和条形图,博主采用的画图工具是python中的seaborn,它的画图效果比matplotlib要好 [1]。

首先需要明确一下直方图和条形图的区别:条形图有空隙,直方图没有,条形图一般用于类别特征,直方图一般用于数字特征(连续型)[2]。

画直方图

import matplotlib.pyplot as plt
import seaborn as sns

def draw_distribution_histogram(nums, path, is_hist=True, is_kde=True, is_rug=False, \
  is_vertical=False, is_norm_hist=False):
  """

  bins: 设置直方图条形的数目
  is_hist: 是否绘制直方图
  is_kde: 是否绘制核密度图
  is_rug: 是否绘制生成观测数值的小细条
  is_vertical: 如果为True,观察值在y轴上
  is_norm_hist: 如果为True,直方图高度显示一个密度而不是一个计数,如果kde设置为True,则此参数一定为True
  """
  sns.set()  #切换到sns的默认运行配置
  sns.distplot(nums, bins=20, hist=is_hist, kde=is_kde, rug=is_rug, \
    hist_kws={"color":"steelblue"}, kde_kws={"color":"purple"}, \
    vertical=is_vertical, norm_hist=is_norm_hist)
  #添加x轴和y轴标签
  plt.xlabel("XXX")
  plt.ylabel("YYY")

  #添加标题
  plt.title("Distribution")
  plt.tight_layout()  # 处理显示不完整的问题
  plt.savefig(path, dpi=300)
  
x=np.random.randn(100)
path = "distribution.jpg"
draw_distribution_histogram(x, path, True, True)

在这里插入图片描述

画条形图/柱状图

def draw_bar_chart(nums, path):
  import pandas as pd
  from collections import Counter
  counter = dict(Counter(nums))
  x, y = [], []
  for line in counter.items():
    x.append(line[0])
    y.append(line[1])
  data = pd.DataFrame({"XXX": x, "YYY": y})
  _, ax = plt.subplots(figsize=(12, 8))
  sns.set()  #切换到sns的默认运行配置
  # palette:调色板,控制不同的颜色style
  barplot = sns.barplot(x="XXX", y="YYY", data=data, palette="Set3", capsize=.2)  # Blues_d, Greens_d, Set3
  barplot_fig = barplot.get_figure()
  ax.set_title('Distribution', fontsize=24)
  ax.set_xlabel("XXX", fontsize=18)
  ax.set_ylabel("YYY", fontsize=18)
  plt.tight_layout()  # 处理显示不完整的问题
  for rect in ax.patches:  # 遍历每个柱子对象
      x_left_edge = rect.get_x()  # 得到柱子左边缘的横坐标值
      bar_width = rect.get_width()  # 得到柱子的宽度
      bar_height = rect.get_height()  # 得到柱子的高度

      # 设置柱子新宽度
      x_center = x_left_edge + bar_width / 2.
      new_bar_width = 0.1
      rect.set_x(x_center-new_bar_width/2.)  # 移动柱子左边缘的横坐标值
      rect.set_width(new_bar_width)

      ax.text(x_center, bar_height,
              bar_height,
              ha='center', va='bottom', rotation=0, color='black', fontsize=12)
  barplot_fig.savefig(path, dpi=300)
  
x = np.random.randint(0, 2, size=100)
path = "bar_chart.jpg"
draw_bar_chart(x, path)

在这里插入图片描述

参考文献

[1] 绘制频率分布直方图的三种方法,总结的很用心!
[2] sns.distplot()用法

  • 13
    点赞
  • 132
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值