Python数据可视化工具matplotlib(四)-- 基本图表绘制

基本图表绘制

图表类别:线形图、柱状图、密度图,以横纵坐标两个维度为主
同时可延展出多种其他图表样式

plt.plot(kind='line', ax=None, figsize=None, use_index=True, title=None, grid=None, legend=False, 
style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, 
rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Series直接生成图表

ts = pd.Series(np.random.randn(50), index=pd.date_range('1/1/2000', periods=50))
ts = ts.cumsum()
# ts.plot()  或者 plt.plot(ts)
ts.plot(kind='line',
       label = 'hehe',
       style = '--.',
       color = 'red',
       alpha = 0.4,
       use_index = True,
       rot = 45,
       grid = True,
       ylim = [-50,50],
       yticks = list(range(-50,50,10)),
       figsize = (10,6),
       title = 'test',
       legend = True)

#plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x')  # 网格
#plt.legend()  # 显示图例
# Series.plot():series的index为横坐标,value为纵坐标
# kind → line,bar,barh...(折线图,柱状图,柱状图-横...)
# label → 图例标签,Dataframe格式以列名为label
# style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)
# color → 颜色,有color指定时候,以color颜色为准
# alpha → 透明度,0-1
# use_index → 将索引用为刻度标签,默认为True
# rot → 旋转刻度标签,0-360
# grid → 显示网格,一般直接用plt.grid
# xlim,ylim → x,y轴界限
# xticks,yticks → x,y轴刻度值
# figsize → 图像大小
# title → 图名
# legend → 是否显示图例,一般直接用plt.legend()
# 也可以 → plt.plot()

在这里插入图片描述

Dataframe直接生成图表

df = pd.DataFrame(np.random.randn(50, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(kind='line',
       style = '--.',
       alpha = 0.4,
       use_index = True,
       rot = 45,
       grid = True,
       figsize = (10,6),
       title = 'test',
       legend = True,
       subplots = False,
       colormap = 'Greens')
# subplots → 是否将各个列绘制到不同图表,默认False
# 也可以 → plt.plot(df)

在这里插入图片描述

柱状图与堆叠图

#plt.plot(kind='bar/barh') , plt.bar()

fig,axes = plt.subplots(4,1,figsize = (10,10))
s = pd.Series(np.random.randint(0,10,16),index = list('abcdefghijklmnop'))  
df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])

s.plot(kind='bar',color = 'b',grid = True,alpha = 0.5,ax = axes[0])  # ax参数 → 选择第几个子图
# 单系列柱状图方法一:plt.plot(kind='bar/barh')

df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])
df.plot(kind='bar',ax = axes[1],grid = True,color=['red','green','blue'])
# 多系列柱状图  #colormap='Reds_r'

df.plot(kind='bar',ax = axes[2],grid = True,colormap='Blues_r',stacked=True) 
# 多系列堆叠图
# stacked → 堆叠

df.plot.barh(ax = axes[3],grid = True,stacked=True)
# 新版本plt.plot.<kind>

在这里插入图片描述

柱状图 plt.bar()

plt.figure(figsize=(10,4))
x = np.arange(10)
y1 = np.random.rand(10)
y2 = -np.random.rand(10)

plt.bar(x,y1,width = 1,facecolor = 'yellowgreen',edgecolor = 'white',yerr = y1*0.1)
plt.bar(x,y2,width = 1,facecolor = 'lightskyblue',edgecolor = 'white',yerr = y2*0.1)
# x,y参数:x,y值
# width:宽度比例
# facecolor柱状图里填充的颜色、edgecolor是边框的颜色
# left-每个柱x轴左边界,bottom-每个柱y轴下边界 → bottom扩展即可化为甘特图 Gantt Chart
# align:决定整个bar图分布,默认left表示默认从左边界开始绘制,center会将图绘制在中间位置
# xerr/yerr :x/y方向error bar

for i,j in zip(x,y1):
    plt.text(i+0.3,j-0.15,'%.2f' % j, color = 'k')
    
for i,j in zip(x,y2):
    plt.text(i+0.3,j+0.15,'%.2f' % -j, color = 'k')
# 给图添加text
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

在这里插入图片描述

外嵌图表plt.table()

# table(cellText=None, cellColours=None,cellLoc='right', colWidths=None,rowLabels=None, rowColours=None, rowLoc='left',
# colLabels=None, colColours=None, colLoc='center',loc='bottom', bbox=None)

data = [[ 66386, 174296,  75131, 577908,  32015],
        [ 58230, 381139,  78045,  99308, 160454],
        [ 89135,  80552, 152558, 497981, 603535],
        [ 78415,  81858, 150656, 193263,  69638],
        [139361, 331509, 343164, 781380,  52269]]
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
df = pd.DataFrame(data,columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail'),
                 index = ['%d year' % x for x in (100, 50, 20, 10, 5)])
print(df)

df.plot(kind='bar',grid = True,colormap='Blues_r',stacked=True,figsize=(10,4))
# 创建堆叠图

plt.table(cellText = data,
          cellLoc='center',
          cellColours = None,
          rowLabels = rows,
          rowColours = plt.cm.BuPu(np.linspace(0, 0.5,5))[::-1],  # BuPu可替换成其他colormap
          colLabels = columns,
          colColours = plt.cm.Reds(np.linspace(0, 0.5,5))[::-1], 
          rowLoc='right',
          loc='bottom')
# cellText:表格文本
# cellLoc:cell内文本对齐位置
# rowLabels:行标签
# colLabels:列标签
# rowLoc:行标签对齐位置
# loc:表格位置 → left,right,top,bottom

plt.xticks([])
# 不显示x轴标注

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jepson2017

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

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

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

打赏作者

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

抵扣说明:

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

余额充值