欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实例:绘制散点直方图

程序员文章站 2022-05-22 13:05:56
...
import matplotlib.pyplot as plt
import numpy as np

# 使用ggplot风格
plt.style.use('ggplot')

# 生成正相关随机散点
x = np.random.randn(200)
y = x + np.random.randn(200) * 0.5

# 设置各图坐标
margin_boder = 0.1
width = 0.6
height = 0.2
margin_between = 0.02

left_s = margin_boder
bottom_s = margin_boder
width_s = width
heigh_s = width

left_x = margin_boder
bottom_x = margin_boder + width + margin_between
heigh_x = height
width_x = width

left_y = margin_boder + width + margin_between
bottom_y = margin_boder
heigh_y = width
width_y = height

# 生成正方形画布
fig = plt.figure(1, figsize=(8, 8))

# 生成坐标系位置参数
rect_s = [left_s, bottom_s, width_s, heigh_s]
rect_x = [left_x, bottom_x, width_x, heigh_x]
rect_y = [left_y, bottom_y, width_y, heigh_y]

# 生成坐标系
axScatter = plt.axes(rect_s)
axHisX = plt.axes(rect_x)
axHisY = plt.axes(rect_y)

# 清楚无用坐标刻度
axHisX.set_xticks([])
axHisY.set_yticks([])

# 设置直方图条形宽度
bin_width = 0.25
xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))])
lim = int(xymax / bin_width + 1) * bin_width

# 设置统一坐标系范围
axScatter.set_xlim(-lim, lim)
axScatter.set_ylim(-lim, lim)

# 绘制散点图
axScatter.scatter(x, y, color='b')

# 绘制直方图
bins = np.arange(-lim, lim + bin_width, bin_width)
axHisX.hist(x, bins=bins, width=[bin_width * 0.9])
axHisY.hist(y, bins=bins, orientation='horizontal',height=[bin_width * 0.9])

axHisX.set_xlim(axScatter.get_xlim())
axHisY.set_ylim(axScatter.get_ylim())

# 设置全局title
fig.suptitle("Scatter and Hist",fontsize=20)

plt.show()

实例:绘制散点直方图

相关标签: matplotlib