用matplotlib进行数据可视化

python官网

一、plot的使用

import pandas as pd
import matplotlib.pyplot as plt

plt.figure(figsize=(5,5))#设置画布的尺寸
plt.title('a',fontsize=20)#标题,并设定字号大小
plt.xlabel('x',fontsize=14)#设置x轴,并设定字号大小
plt.ylabel('y',fontsize=14)#设置y轴,并设定字号大小
x=[1,2,3,4,5]
y=[1,4,9,16,25]
plt.plot(x,y,color='b',linewidth=1.5,linestyle='--',label='tuli',marker='o')

plt.legend(loc=1)#图例展示位置,数字代表第几象限
plt.show()#显示图像

坐标轴换不同的单位

plt.xticks([0,5,10,15,20],['a','b','c','d','e'])
#前面是x轴每个点间距,后面是每个点的标签

坐标轴范围

plt.xlim((0,2))
plt.ylim((2,4))
参数解释
x,y表示x轴与y轴对应的数据
color折线的颜色
marker折线上数据点处的类型
linestyle折线类型
linewith线条粗细(数值)
alpha点的透明度(0~1)
label图例的内容

color

类型样式
‘b’蓝色
‘g’绿色
‘r’红色
‘y’黄色
‘k’黑色
‘w’白色

marker

类型样式
‘.’点标记
‘,’像素标记
‘o’圆圈标记
‘^’三角形标记
‘*’星标
‘+’加号标记

linestyle

类型样式
‘-’实线
‘–’虚线
‘-.’点划线
‘:’点线

其他参数参考

二、subplot(画子图)

1.subplot

# 两行一列的图,第三个参数表示第几个图
x=[1,2,3,4,5]
y=[1,4,9,16,25]

plt.subplot(2,1,1)
plt.plot(x,y,color='b')
plt.subplot(2,1,2)
plt.plot(x,y,color='r')

plt.show()

2.subpots

x=[1,2,3,4,5]
y1=[1,4,9,16,25]
y2=[1,2,3,4,5]
#ax是个数组,可以访问子图
figure, ax=plt.subplots(2,2)
ax[0][0].plot(x, y1)
ax[0][1].plot(x, y2)

plt.show()

三、通过Series和DataFrame绘制plot

1.在Series中

1)subplot
s1 = pd.Series(np.random.randn(1000)).cumsum()
# kind参数是修改画图类型
s1.plot(kind='line', grid=True,style='--')
plt.show()
2)subplot
s1 = pd.Series(np.random.randn(1000)).cumsum()
fig, ax = plt.subplots(2,1)
s1.plot(ax=ax[0])
s1.plot(ax=ax[1])
plt.show()

2.在DataFrame中

# 创建一个5行4列的DataFrame
df = pd.DataFrame(
    np.random.randint(1,10,20).reshape(5,4),
    columns = {'A','B','C','D'} )
df.plot(kind='bar') #bar是柱形图,默认为line
plt.show()

#kind=‘barh’是横柱形图
#加个stacked=Ture 会堆叠
#kind=‘area’可以看看

在这里插入图片描述

三、图形

1.条形图

条形图是分类数据,直方图是数值型数据

1)竖直的
plt.bar([1, 3, 5, 7, 9], [5, 4, 8, 12, 7], label='graph 1')
plt.bar([2, 4, 6, 8, 10], [4, 6, 8, 13, 15], label='graph 2')
# 参数
# x: 条形图x轴
# y:条形图的高度
# width:条形图的宽度 默认是0.8
# bottom:条形底部的y坐标值 默认是0
# align:center / edge 条形图是否以x轴坐标为中心点或者是以x轴坐标为边缘
plt.legend()
plt.show()
2)水平和竖直的一起
np.random.seed(1) #让随机数是固定值
x = np.arange(5)
y = np.random.randn(5)
fig ,ax = plt.subplots(1,2)
ax[0].bar(x,y,color='red',align='center')
ax[1].barh(x,y,color='blue')

ax[0].axhline(0,color='black',linewidth=2)
ax[1].axvline(0,color='gray',linewidth=2)
plt.show()

2.直方图

用于统计数据出现的次数或频率

1)单个图
salary = [2500, 3300, 2700, 5600, 6700, 5400, 3100, 3500, 7600, 7800,
          8700, 9800, 10400]

group = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000]
plt.hist(salary,group,histtype='bar',rwidth=0.8)
plt.show()

在这里插入图片描述

2)多个图
np.random.seed(1)

n_bins = 10  #几条数据
x = np.random.randn(1000,3)
fig,ax = plt.subplots(2,2)
colors=['red','yellow','gray']
ax[0][0].hist(x,n_bins,histtype='bar',color=colors,label=colors)
ax[0][0].legend()
ax[0][0].set_title('title')

ax[0][1].hist(x,10,histtype='barstacked')
ax[1][0].hist(x,rwidth=0.8)
ax[1][1].hist(x,rwidth=0.8)
plt.show()

在这里插入图片描述

3.饼图

1)单个图
beijing = [17,17,23,43]

label = ['2-3 years','3-4 years','4-5 years','5+ years']
color = ['red','green','yellow','purple']

indic = []

#我们将数据最大的突出显示
for value in beijing:
    if value == max(beijing):
        indic.append(0.1)
    else:
        indic.append(0)

plt.pie(
    beijing,
    labels=label,
    colors=color,
    startangle=90,#起始绘制角度,x开始逆时针
    shadow=True,#是否绘制阴影
    explode=tuple(indic),#tuple方法用于将列表转化为元组,分割时要传入0.1
    autopct='%1.1f%%',#比例竖直显示的格式
    pctdistance=0.9 #比例显示的数据距离中心的距离,默认0.6
)


plt.title('beijing-ages')
plt.show()

在这里插入图片描述

2)多个图
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, (ax1, ax2) = plt.subplots(2)
ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True)
ax1.axis('equal')
ax2.pie(sizes, autopct='%1.2f%%', shadow=True, startangle=90, explode=explode,
    pctdistance=1.12)
ax2.axis('equal')
ax2.legend(labels=labels, loc='upper right')

plt.show()

在这里插入图片描述

4.散点图

1)单个图

import matplotlib.pyplot as plt
import numpy as np

xValue = list(range(0, 101))
yValue = [x * np.random.rand() for x in xValue]

plt.title('a')

plt.xlabel('x-value')
plt.ylabel('y-label')
# plt.scatter(x, y, s, c, marker)
# x: x轴坐标
# y:y轴坐标
# s:点的大小/粗细 标量或array_like 默认是 rcParams['lines.markersize'] ** 2
# c: 点的颜色 
# marker: 标记的样式 默认是 'o'
plt.legend()

plt.scatter(xValue, yValue, s=20, c="#ff1212", marker='o')
plt.show()

在这里插入图片描述

5.箱图

data=np.arange(1000)
data2=np.arange(500)

fig,ax = plt.subplots(2,1)
ax[0].boxplot(data)


ax[1].boxplot(data2,vert=False) #控制方向
plt.show()

在这里插入图片描述

6.泡泡图

散点图的一种特殊形式

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2  # 0 to 15 point radii

plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值