1. Matplotlib绘制柱形图/柱状图/条形图
柱状图是一种用矩形柱来表示数据分类的图表,柱状图可以垂直绘制,也可以水平绘制,它的高度与其表示的数据成正比关系
import numpy as np
import pandas as pd
import matplotlib. pyplot as plt
% matplotlib inline
plt. rcParams[ 'font.sans-serif' ] = "SimHei"
plt. rcParams[ "axes.unicode_minus" ] = False
% config Inlinebackend. figure_format = "svg"
2. 简单柱状图
x = [ "语文" , "数学" , "英语" , "Python" , "化学" ]
y = [ 20 , 10 , 40 , 60 , 10 ] plt. figure( figsize= ( 5 , 3 ) )
plt. bar( x, y)
<BarContainer object of 5 artists>
3. Pandas获取Excel数据
df = pd. read_excel( "05_bar.xlsx" , sheet_name= "bar1" )
df
年份 销售额 0 2014 1962035 1 2015 2838693 2 2016 2317447 3 2017 2335002 4 2018 2438570 5 2019 1675591 6 2020 3568120
x, y = df[ "年份" ] , df[ "销售额" ]
plt. figure( figsize= ( 5 , 3 ) ) plt. title( "年度销售额" )
plt. xlabel( "年份" )
plt. ylabel( "销售额" )
plt. bar( x, y, width= 0.8 )
for a, b in zip ( x, y) : plt. text( x= a, y= b, s= "{:.1f}万" . format ( b/ 10000 ) , ha= "center" , fontsize= 9 )
4. 一次绘制多个柱形图
df2 = pd. read_excel( "05_bar.xlsx" , sheet_name= "bar2" )
df2
年份 北区 中区 南区 0 2014 634704 534917 792414 1 2015 1218844 746554 873295 2 2016 1013322 904058 400067 3 2017 1068521 12269 1254212 4 2018 419352 526985 1492233 5 2019 1190076 117510 368005 6 2020 695421 1433961 1438738
x, y1, y2, y3 = df2[ "年份" ] , df2[ "北区" ] , df2[ "中区" ] , df2[ "南区" ]
plt. figure( figsize= ( 5 , 3 ) )
plt. title( "年销售额" )
plt. xlabel( "年份" )
plt. ylabel( "销售额" )
w = 0.2
plt. bar( x- w, y1, width= w, label= "北区" )
plt. bar( x, y2, width= w, label= "中区" )
plt. bar( x+ w, y3, width= w, label= "南区" )
plt. legend( )
<matplotlib.legend.Legend at 0x1771356c610>
plt. figure( figsize= ( 5 , 3 ) )
plt. title( "年销售额" )
plt. xlabel( "年份" )
plt. ylabel( "销售额" )
plt. bar( x, y1, label= "北区" )
plt. bar( x, y2, label= "中区" , bottom= y1)
plt. bar( x, y3, label= "南区" , bottom= y1+ y2)
plt. legend( )
<matplotlib.legend.Legend at 0x17713808a10>
5. 条形图
plt. barh( x, y1)
<BarContainer object of 7 artists>