Matplotlib图表的基本元素--基本图表绘制

1.1 Series与DataFrame绘图

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)

参数含义:

  • 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()
ts=pd.Series(np.random.randn(365),index=pd.date_range('1/1/2019',periods=365))
ts=ts.cumsum()
ts.plot(kind='line',
       label = "what",
       style = '--.',
       color = 'green',
       alpha =0.4,
       use_index = True, # 把对应的月份显示出来
       rot = 45,
       grid = True,
       ylim = [-50,50],
       yticks = list(range(-50,50,10)),
       figsize = (8,4),
       title = 'TEST_TEST',
       legend = True)

# 对网格项进行更加细致的设置,可以单独用plt修改方法参数
#plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x')  # 网格
plt.legend() # 几乎没有变化

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

1.2 柱状图

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

# 创建一个新的figure,并返回一个subplot对象的numpy数组
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'])

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

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

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

df.plot(kind='barh',ax=axes[3],grid=True,stacked=True,colormap='BuGn_r')
#df.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')

plt.bar()

  • x,y参数:x,y值
  • width:宽度比例
  • facecolor柱状图里填充的颜色、edgecolor是柱状图里边框的颜色
  • left-每个柱x轴左边界,bottom-每个柱y轴下边界 → bottom扩展即可化为甘特图 Gantt Chart
  • align:决定整个bar图分布,默认left表示默认从左边界开始绘制,center会将图绘制在中间位置
  • xerr/yerr :x/y方向error bar,即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)

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

1.3 面积图

  • stacked:是否堆叠,默认情况下,区域图被堆叠
  • 为了产生堆积面积图,每列必须是正值或全部负值!
  • 当数据有NaN时候,自动填充0,图标签需要清洗掉缺失值
fig,axes=plt.subplots(2,1,figsize=(8,6))

df1=pd.DataFrame(np.random.rand(10,4),columns=['a','b','c','d'])
df2=pd.DataFrame(np.random.rand(10,4),columns=list('abcd'))

df1.plot(kind='area',colormap='Greens_r',alpha=0.5,ax=axes[0])
# df1.plot.area(colormap='Greens_r',alpha=0.5,ax=axes[0])
df2.plot.area(stacked=False,colormap='Set2',alpha=0.5,ax=axes[1])

'''Colormap Green_r is not recognized. Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r'''

1.4 填图

在有subplot子图的情况下必须有fig、axes接收参数。

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() # 即可把label标签的名称显示出来
    axes[i].grid()
# 添加图例、格网

1.5 饼图

plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)
  • 第一个参数:数据
  • explode:指定每部分的偏移量
  • labels:标签
  • colors:颜色
  • autopct:饼图上的数据标签显示方式
  • pctdistance:每个饼切片的中心和通过autopct生成的文本开始之间的比例
  • labeldistance:被画饼标记的直径,默认值:1.1
  • shadow:阴影
  • startangle:开始角度
  • radius:半径
  • frame:图框
  • counterclock:指定指针方向,顺时针或者逆时针
# 不必仅仅拘泥于Series类型的,Dataframe数据帧格式也可,但只能是针对一列。
s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
#s = pd.DataFrame(np.random.rand(4,1),index=list('abcd'))
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)

1.6 直方图

plt.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, 
histtype='bar', align='mid', orientation='vertical',rwidth=None, log=False, color=None, label=None, 
stacked=False, hold=None, data=None, **kwargs)
  • bin:箱子的宽度
  • normed 标准化
  • histtype 风格,bar,barstacked,step,stepfilled
  • orientation 水平还是垂直{‘horizontal’, ‘vertical’}
  • align : {‘left’, ‘mid’, ‘right’}, optional(可选择的、随意的对齐方式)
  • stacked:是否堆叠
# 直方图
s = pd.Series(np.random.randn(1000))
s.hist(bins = 20,
       histtype = 'bar',
       align = 'mid',
       orientation = 'vertical',
       alpha=0.5,
       normed =True) #注意:The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead
# 密度图
s.plot(kind='kde',style='k--')

# 堆叠直方图

plt.figure(num=1)
df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
                    'c': np.random.randn(1000) - 1, 'd': np.random.randn(1000)-2},
                   columns=['a', 'b', 'c','d'])
df.plot.hist(stacked=True,
             bins=20,
             colormap='Greens_r',
             alpha=0.5,
             grid=True)
# 使用DataFrame.plot.hist()和Series.plot.hist()方法绘制,或用plot(kind='hist')绘制

df.hist(bins=50)
# 生成以上4个直方图

1.7 散点图

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)
  • s:散点的大小
  • c:散点的颜色
  • vmin,vmax:亮度设置,标量
  • cmap:colormap
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_r',
           c = y, # 可以为'g'...
           alpha = 0.8,)
plt.grid()

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值