matplotlib seaborn 数据可视化(1)——1维数据折线图、散点图、条形图、直方图

1. 折线图/描点图

即描点图,以给出的索引(或无索引,默认创建)绘制折线。

import numpy as np
import math
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
%matplotlib

#指定数量或步长
num=1000
x_1 = np.linspace(0,10,num)
step=10/num
x_2 = np.arange(0,10,step)
#按照解析表达式
y_1 = np.sin(x_1**2)
mu ,sigma = 5, 2
y_2 = (1/np.sqrt(2*math.pi)*sigma)*np.exp(-(x_2-mu)**2 / 2*sigma**2)
#折线图
fig = plt.figure(1,figsize=(8,8))
ax = fig.add_subplot(221)
ax.plot(x_1,y_1)
ax.set_title(r"matplotlib: $y_1=\sin(x_1)$")
ax.set_xlabel(r"$x_1$")
ax.set_ylabel(r"$y_1$")
ax = fig.add_subplot(222)
ax.plot(x_2,y_2)
ax.set_title(r"matplotlib: $y_2$ =Normal$(x|\mu,\sigma)$")
ax.set_xlabel(r"$x_2$")
ax.set_ylabel(r"$y_2$")
#使用sns.lineplot需要用到DataFrame
df = pd.DataFrame({'x_1':x_1,'x_2':x_2,'y_1':y_1,'y_2':y_2})
ax = fig.add_subplot(223)
ax.set_title(r"seaborn: $y_1=\sin(x_1)$")
ax.set_xlabel(r"$x_1$")
ax.set_ylabel(r"$y_1$")
sns.lineplot(data=df,x='x_1',y='y_1')
ax = fig.add_subplot(224)
ax.set_title(r"seaborn: $y_2$ =Normal$(x|\mu,\sigma)$")
sns.lineplot(data=df,x='x_2',y='y_2')
ax.set_xlabel(r"$x_2$")
ax.set_ylabel(r"$y_2$")
plt.show()

运行结果:
lineplot
适用于按照解析表达式分布的数据,可以呈现该式所反映的数量关系,不适用于依据某分布生成的随机数。描点图只对数据做最原本的直观反映。

2. 散点图

与描点图类似,只对数据做最原本的直观反映,但不绘制点间连线。

#散点图
fig = plt.figure(2,figsize=(8,8))
ax = fig.add_subplot(221)
ax.set_title(r"matplotlib: $y_1=\sin(x_1)$")
ax.set_xlabel(r"$x_1$")
ax.set_ylabel(r"$y_1$")
ax.scatter(x_1,y_1)
ax = fig.add_subplot(222)
ax.set_title(r"matplotlib: $y_2$ =Normal$(x|\mu,\sigma)$")
ax.set_xlabel(r"$x_2$")
ax.set_ylabel(r"$y_2$")
ax.scatter(x_2,y_2)
ax = fig.add_subplot(223)
ax.set_title(r"seaborn: $y_1=\sin(x_1)$")
ax.set_xlabel(r"$x_1$")
ax.set_ylabel(r"$y_1$")
sns.scatterplot(data=df,x='x_1',y='y_1')
ax = fig.add_subplot(224)
ax.set_title(r"seaborn: $y_2$ =Normal$(x|\mu,\sigma)$")
ax.set_xlabel(r"$x_2$")
ax.set_ylabel(r"$y_2$")
sns.scatterplot(data=df,x='x_2',y='y_2')
plt.show()

运行结果:
scatterplot

3. 柱状图/条形图

条形图适用于具有多索引、多类别且类别具有多条数据的数据,见seaborn内置数据集saeborn.datasets

#准备数据

#1.词条
NameList = ["Batman","Superman","Clown","Avengers","Thor","Iron Man"]

#2.数据
Score = [4.4, 3.9, 4.9, 3.6, 3.1, 3.3]
Booking = [3.2, 6.7, 1.2, 8.7, 4.8, 9.0]
Cost = np.around(np.random.uniform(1,3,6),decimals=2).tolist()

#3.索引
#主索引
index = np.arange(len(NameList))
#设置宽度
width = 0.2
#根据需求,以主索引为基准,以宽度为单位,控制其余索引
Booking_index = [i+width for i in index]
Cost_index = [i-width for i in index]

#打印图像
#1.设置画板
fig = plt.figure(3,figsize=(12,12))
ax = fig.add_subplot(221)
#2.绘图
#在图像中显示索引,传入‘主索引’index、‘词条’NameList和‘词条显示角度’rotation
plt.xticks(index,NameList)
#输出三组条形图
ax.bar(x=index, height=Score, width=width, hatch='', color='red', edgecolor='k', label='Score', align='center', fill=False )
ax.bar(Booking_index,Booking,width,hatch='xxx',color='white',ec='k',label='Booking')
ax.bar(Cost_index,Cost, width,hatch='//',color='white',ec='k',label='Cost')

"""
x:x轴索引
height:y轴数据         
width:每个条形宽度,默认0.8  
hatch:填充,取值在{'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}  
color:条形填充颜色,可选rgb值
edgecolor:条形边缘颜色
label:该组数据标签,在图例中显示
align:'edge'表示条形左边缘与索引点对齐,'center'表示条形在索引点中心对齐
fill:控制颜色是否填充
详情通过help(plt.bar)查看
"""
#3.条形顶部显示具体数据
for idx, text in zip(index, Score):
        ax.text(idx, text, text, ha='center', va='bottom',fontsize=9
        #,bbox=dict(facecolor='red', alpha=0.5)
        )
for idx, text in zip(Booking_index, Booking):
        ax.text(idx, text, text, ha='center', va='bottom',fontsize=9
        #,bbox=dict(facecolor='green', alpha=0.5)
        )
for idx, text in zip(Cost_index, Cost):
        ax.text(idx, text, text, ha='center', va='bottom',fontsize=9
        #,bbox=dict(facecolor='blue', alpha=0.5)
        )
"""
Help on function text in module matplotlib.pyplot:

text(x, y, s, fontdict=None, **kwargs)
    Add text to the axes.
    
    Add the text *s* to the axes at location *x*, *y* in data coordinates.
索引在数据标记的‘中间’、‘右侧’或‘左侧’,推荐‘中间’
        horizontalalignment or ha: {'center', 'right', 'left'}
数据标记在条形顶端的‘中间’、‘顶部对齐’、‘底部对齐’、‘基准对齐’或‘中间基准对齐’,推荐‘底部对齐’
        verticalalignment or va: {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
数据标记突出显示为带颜色的盒子,如填充颜色facecolor为‘红’,透明度alpha为0.5
        bbox: dict with properties for `.patches.FancyBboxPatch`
        example:bbox=dict(facecolor='red', alpha=0.5)
详情通过help(plt.text)查看
"""
#4.控制图例位置‘左上’upper left,也可以设置为‘右上’upper right
plt.legend(loc='upper left')
ax.set_title('matplotlib: summary')
#DataFrame
dtfm = pd.DataFrame({"name":NameList,"score":Score,"booking":Booking,"cost":Cost})
ax = fig.add_subplot(222)
ax.set_title('seaborn: score')
sns.barplot(data=dtfm,x="name",y="score")
ax = fig.add_subplot(223)
ax.set_title('seaborn: booking')
sns.barplot(data=dtfm,x="name",y="booking")
ax = fig.add_subplot(224)
ax.set_title('seaborn: cost')
sns.barplot(data=dtfm,x="name",y="cost")
plt.show()

运行结果:
barplot
seaborn的条形图输出函数barplot似乎不能在同索引上绘制不同数据,自由度低于matplotlib,其主要功能在于做更高级统计可视化,详见help(sns.barplot)

4. 直方图

直方图适用于具有较强统计性质的任务,而非直观呈现任务,也不适用于经过完全统计之后的数据。

#准备数据
data = np.around(np.random.normal(3,2,100),decimals=2).tolist()
#设置组距
width = 0.5
#计算组数,设置索引
num_bins = int((max(data)- min(data))//width)
#设置画板
fig = plt.figure(4,figsize=(8,8))
ax = fig.add_subplot(211)
#绘制,显示为“密度”形式
ax.hist(data,num_bins,density=True)
#设置x轴
plt.xticks(np.arange(min(data),max(data)+width,width))
#使用seaborn,显示为“密度”形式,同时显示核密度估计曲线
ax = fig.add_subplot(212)
sns.histplot(data,stat='density',kde=True)
#从图像来看,sns.histplot比plt.hist呈现效果更完善
plt.show()

运行结果:
histplot
更多信息见matplotlibseaborn官方文档、示例以及使用help()函数查看。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fanshaoliang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值