绘制各种图,pandas直接生成、常规绘图

# -*- coding: utf-8 -*-
import time
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pandas as pd
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong']
mpl.rcParams['axes.unicode_minus'] = False
#折线图、柱状图,柱状堆叠图、面积图、填图、饼图、直方图、堆叠直方图、密度图、散点图、箱型图
#line、 bar、   stacked bar、area、fill、pie、hist、stacked hist、kde、scatter、box
#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)
"""
两种方法生成graph
方法一:pandas,  pd.plot()
1、这种数据会使用索引
2、Series:可以使用kind= ['line','bar','area','no—fill','pie','hist','kde','no-scatter','box']
    因为只有一个,所以不能够stacked=True
3、DataFrame:可以使用,
            ['line','stacked line','bar','stacked bar','area','stacked area',
             'no-fill','no-stacked fill','pie','stacked pie','hist','stacked hist',
             'kde','stacked kde','scatter','stacked scatter','box','stacked box']
书写方式可以这样
series_or_dataframe.plot(kind = 'a_kind')<===>series_or_dataframe.plot.a_kind()
方法二:常规序列
plt.plot(xdata,ydata)
plt.bar()
方法三:使用pandas,这个就是方法1将kind的值提出来
series_or_dataframe.hist
series_or_dataframe.boxplot
"""
"""
只能用一种方法
fill 填图
和坐标轴填充用fill,axes[0,1].fill()/plt.fill()
两个函数之间的填充: axes[0,0].fill_between()/plt.fill_between()
scatter 散点图
plt.scatter需要将横纵坐标都放进去,plt.scatter() axes[0,1].scatter()
"""
#pandas直接生成图
def series_graph():
    a = pd.Series(np.random.randint(0, 10, 10))
    a.plot(kind = 'line')
    # kind → line,bar,barh,hist..(折线图,柱状图,柱状图-横...)
    # style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)
    # color → 颜色,有color指定时候,以color颜色为准
    # alpha → 透明度,0-1
    # use_index → 将索引用为刻度标签,默认为True
    # rot → 旋转刻度标签,0-360
    # grid → 显示网格,一般直接用plt.grid
    # figsize → 图像大小
    #其他的参数还可以根据基本元素设置,在matplotlib_basic_element_and_argument
    plt.show()
def dataframe_graph():
    # line、 bar、   stacked bar、area、fill、pie、hist、stacked hist、kde、scatter、box
    a = pd.DataFrame(np.random.randint(10,size=(10,4)),columns = [1,1,1,2])
    print(a)
    a.plot(stacked= True,kind = 'pie')
    plt.show()
def series_line_subplot():
    a = pd.Series(np.random.randint(0,10,100))
    print(a)
    b = pd.Series(np.random.randint(10,20,100))
    print(b)
    fig, axes = plt.subplots(2,2)
    axes[0,0].plot(a)
    axes[1,1].plot(b)
    plt.show()
#不使用pandas
def line_subplot():
    a = np.arange(100)
    fig, axes = plt.subplots(2,2)
    axes[0,0].plot(a)
    plt.show()
def dataframe_line_subplot():
    a = pd.DataFrame(np.random.randint(10, size=(10, 4)), columns=['a', 'b', 'c', 'd'])
    print(a)
    b = pd.DataFrame(np.random.randint(10, size=(10, 4)), columns=['a', 'b', 'c', 'd'])
    print(b)
    fig,axes = plt.subplots(2,2)
    axes[0,0].plot(a)
    axes[1,1].plot(b)
    plt.show()
if __name__=='__main__':
    F = 1

    if F == -1:
        series_graph()
        print("""'Series:可以使用kind= ['line','bar(h)','area','no—fill','pie','hist','kde','no-scatter','box']
    因为只有一个,所以不能够stacked=True'""")
    elif F ==-2:
        dataframe_graph()
        print("""DataFrame:可以使用,
            ['line','stacked line','bar(h)','stacked bar','area','stacked area',
             'no-fill','no-stacked fill','pie','stacked pie','hist','stacked hist',
             'kde','stacked kde','scatter','stacked scatter','box','stacked box']""")

    elif F == 1:       line()
    elif F == 2:       bar()
    elif F == 3:       pie()
    elif F == 4:       hist();print("'series.hist'")
    elif F == 5:       box1()
    elif F == 6:       box2()
    elif F == 11:      fill()
    elif F == 12:      scatter()

 折线图

#折线图
def line():
    a = np.arange(100)
    print(a)
    plt.plot(a,a)
    plt.xlabel('我是')
    plt.show()
散点图
def scatter():
    # plt.scatter()散点图
    # plt.scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None,
    # alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)

    plt.figure(figsize=(8, 6))
    x = np.random.randn(1000)
    y = np.random.randn(1000)
    plt.scatter(x, y, marker='.',
                s=np.random.randn(1000) * 100,
                cmap='Reds',
                c=y,
                alpha=0.8, )
    plt.grid()
    # s:散点的大小
    # c:散点的颜色
    # vmin,vmax:亮度设置,标量
    # cmap:colormap
    plt.show()
柱状图
def bar():
    # 柱状图 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方向误差

    for i, j in zip(x, y1):
        plt.text(i + 0.3, j - 0.15, '%.2f' % j, color='white')
    for i, j in zip(x, y2):
        plt.text(i + 0.3, j + 0.05, '%.2f' % -j, color='white')
    plt.axvline(0,color = 'r', linewidth=3)#放置0刻度线
    plt.axhline(0,color = 'k',linewidth=3)#放置纵向0刻度线
    #每个不同的bar设置不同的颜色
    bar = plt.bar(x, y1, width=1, facecolor='yellowgreen', edgecolor='white', yerr=y1 * 0.1)
    for bar, height in zip(bar, y1):
        if height < 0:
            bar.set(color='lightgreen')
    # 给图添加text
    # zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
    plt.show()

#显示多组柱状图
import matplotlib.pyplot as plt

a = [1,2,3]
b = [4,5,6]
d = [7,8,9]
y = [1,2,3]

width = 0.2
plt.bar([i-width for i in y],a,color = 'r',width=width)
plt.bar(y,b,color = 'k',width=width)
plt.bar([i+width for i in y],d,color='g',width=width)
plt.show()

import matplotlib.pyplot as plt
# 获取bar的长宽高的信息,来设置文本
x = [10, 20,30]
y = [1,2,3]
bars = plt.bar(x,y,width=5)
for bar,data in zip(bars, x):
    x = bar.get_height()#bar的高度
    y = bar.get_x()#bar的宽度的其实位置
    m = bar.get_width()#bar的宽度
    n = bar.get_y()#bar的底部
    print(x,y,m,n)
    plt.text(y,x,data)
plt.show()

import matplotlib.pyplot as plt
#在bar中绘制不同的线来区分
x = list(range(10,18))
y = list(range(1,9))
bars = plt.bar(x,y)
patterns = ('-','+','×','*','\','o','--','.')
for bar , pattern in zip(bars, patterns):
    bar.set_hatch(pattern)
plt.show()

直方图、密度图

def hist():
    # 直方图+密度图

    s = pd.Series(np.random.randn(1000))
    s.hist(bins=20,
           histtype='bar',
           align='mid',
           orientation='vertical',
           alpha=0.5,
           normed=True)
    # bin:箱子的宽度
    # normed 标准化
    # histtype 风格,bar,barstacked,step,stepfilled
    # orientation 水平还是垂直{‘horizontal’, ‘vertical’}
    # align : {‘left’, ‘mid’, ‘right’}, optional(对齐方式)
    s.plot(kind='kde', style='k--')
    plt.show()
    # 密度图
import matplotlib.pyplot as plt

a = [1,2,3,1]
plt.hist(a)
plt.show()
如果有多个直方图,那么可以用alpha这个透明度来区分
直方图是什么呢?
    将所有的data进行整理,data中每个取值有多少个。

饼图

饼图
def pie():
    s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
    plt.axis('equal')  # 保证长宽相等
    plt.pie(s,
            explode=[0.1, 0, 0, 0],
            labels=s.index,
            colors=['r', 'g', 'b', 'c'],
            autopct='%.2f%%',
            pctdistance=0.6,
            labeldistance=1.2,
            shadow=True,
            startangle=0,
            radius=1.5,
            frame=False)
    plt.show()
    print(s)
    # 第一个参数:数据
    # explode:指定每部分的偏移量,饼图之间都是分开的
    # labels:标签
    # colors:颜色
    # autopct:饼图上的数据标签显示方式
    # pctdistance:每个饼切片的中心和通过autopct生成的文本开始之间的比例
    # labeldistance:被画饼标记的直径,默认值:1.1
    # shadow:阴影
    # startangle:开始角度
    # radius:半径
    # frame:图框
    # counterclock:指定指针方向,顺时针或者逆时针

import matplotlib.pyplot as plt

boy = 43
girl = 54

labels = ['girl','boy']#饼图外面的类别指示
patches,texts, autotexts = plt.pie([girl,boy],labels = labels,autopct='%1.1f%%', colors = ['r','b'],explode = [0.05,0.05])
#labels:饼图外面的类别指示
#autopct:饼图上的百分比信息,当然自己也可以放置别的
#texts:饼图外面的文字,也就是类别信息
for text in autotexts:
    text.set_color('white')
    text.set_fontsize(16)
for t in texts:
    t.set_color('black')
    t.set_fontsize(16)
plt.show(

箱型图

def box1():
    # 箱型图
    # plt.plot.box()绘制

    fig, axes = plt.subplots(2, 1, figsize=(10, 6))
    df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
    color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')
    # 箱型图着色
    # boxes → 箱线
    # whiskers → 分位数与error bar横线之间竖线的颜色
    # medians → 中位数线颜色
    # caps → error bar横线颜色
###########################################
    df.plot.box(ylim=[0, 1.2],
                grid=True,
                color=color,
                ax=axes[0])
    # color:样式填充
###########################################
    df.plot.box(vert=False,
                positions=[1, 4, 5, 6, 8],
                ax=axes[1],
                grid=True,
                color=color)
    # vert:是否垂直,默认True
    # position:箱型图占位
    plt.show()
def box2():
    # 箱型图
    # plt.boxplot()绘制
    # pltboxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None,
    # usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None,
    # labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_xticks=True, autorange=False,
    # zorder=None, hold=None, data=None)

    df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
    plt.figure(figsize=(10, 4))
    # 创建图表、数据

    f = df.boxplot(sym='o',  # 异常点形状,参考marker
                   vert=True,  # 是否垂直
                   whis=1.5,  # IQR,默认1.5,也可以设置区间比如[5,95],代表强制上下边缘为数据95%和5%位置
                   patch_artist=True,  # 上下四分位框内是否填充,True为填充
                   meanline=False, showmeans=True,  # 是否有均值线及其形状
                   showbox=True,  # 是否显示箱线
                   showcaps=True,  # 是否显示边缘线
                   showfliers=True,  # 是否显示异常值
                   notch=False,  # 中间箱体是否缺口
                   return_type='dict'  # 返回类型为字典
                   )
    plt.title('boxplot')
    print(f)

    for box in f['boxes']:
        box.set(color='b', linewidth=1)  # 箱体边框颜色
        box.set(facecolor='b', alpha=0.5)  # 箱体内部填充颜色
    for whisker in f['whiskers']:
        whisker.set(color='k', linewidth=0.5, linestyle='-')
    for cap in f['caps']:
        cap.set(color='gray', linewidth=2)
    for median in f['medians']:
        median.set(color='DarkBlue', linewidth=2)
    for flier in f['fliers']:
        flier.set(marker='o', color='y', alpha=0.5)
    # boxes, 箱线
    # medians, 中位值的横线,
    # whiskers, 从box到error bar之间的竖线.
    # fliers, 异常值
    # caps, error bar横线
    # means, 均值的横线,

填图

def fill():
    # 填图

    fig, axes = plt.subplots(2, 1, figsize=(8, 6))

    x = np.linspace(0, 1, 500)
    y1 = np.sin(4 * np.pi * x) * np.exp(-5 * x)
    y2 = -np.sin(4 * np.pi * x) * np.exp(-5 * x)
    axes[0].fill(x, y1, 'r', alpha=0.5, label='y1')
    axes[0].fill(x, y2, 'g', alpha=0.5, label='y2')
    # 对函数与坐标轴之间的区域进行填充,使用fill函数
    # 也可写成:plt.fill(x, y1, 'r',x, y2, 'g',alpha=0.5)#这个是单个填图的时候

    x = np.linspace(0, 5 * np.pi, 1000)
    y1 = np.sin(x)
    y2 = np.sin(2 * x)
    axes[1].fill_between(x, y1, y2, color='b', alpha=0.5, label='area')
    # 填充两个函数之间的区域,使用fill_between函数

    for i in range(2):
        axes[i].legend()
        axes[i].grid()
    plt.show()
    # 添加图例、格网

等高图

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10,10,5)
y = np.linspace(-20,10,5)
"""
绘制二维图
    需要知道的信息
        我们需要知道自变量x的取值,以及y对应的取值。
    做法:
        将每个x带入函数即可的得到y
绘制三维图
    需要知道的信息
        我们需要知道自变量x和y的取值,也就是所有xy的取值组合,
        也就是x取第一个值,对应所有的y取值
             x取第二个值,对应所有的y取值
             。。。
        然后将上述各种组合带入函数中就可以得到z轴
    
"""
xx,yy = np.meshgrid(x,y)
print(xx)
print(yy)
zz = xx**2 + yy**2
plt.figure()
plt.contour(xx,yy,zz,20)#contourf这个会填充进去颜色
plt.show()


xx,yy = np.meshgrid(x,y)
上面的结果
    将下面的两张表一对一的组合起来就是一个平面的各个坐标图
    xx将x复制5份
    yy将y^T复制5份
    [[-10.  -5.   0.   5.  10.]
     [-10.  -5.   0.   5.  10.]
     [-10.  -5.   0.   5.  10.]
     [-10.  -5.   0.   5.  10.]
     [-10.  -5.   0.   5.  10.]]
    [[-20.  -20.  -20.  -20.  -20. ]
     [-12.5 -12.5 -12.5 -12.5 -12.5]
     [ -5.   -5.   -5.   -5.   -5. ]
     [  2.5   2.5   2.5   2.5   2.5]
     [ 10.   10.   10.   10.   10. ]]

三维图方式1

三维散点
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 16:37:21 2015

@author: Eddy_zheng
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

data = np.random.randint(0, 255, size=[40, 40, 40])

x, y, z = data[0], data[1], data[2]
ax = plt.subplot(111, projection='3d')  # 创建一个三维的绘图工程
#  将数据点分成三部分画,在颜色上有区分度
ax.scatter(x[:10], y[:10], z[:10], c='y')  # 绘制数据点
ax.scatter(x[10:20], y[10:20], z[10:20], c='r')
ax.scatter(x[30:40], y[30:40], z[30:40], c='g')

ax.set_zlabel('Z')  # 坐标轴
ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.show()

三维图方式二

三维面
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 16:17:13 2015

@author: Eddy_zheng
"""

from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')

plt.show()

三维旋转角度设置

ax.view_init(elev=32,azim=90)
三维图旋转角度
azim:正常的绘制xyz坐标的时候,也就是正视图,做转角度
elev:xy平面上翻角度
原文地址:https://www.cnblogs.com/yunshangyue71/p/13584374.html