python可视化(一)-条形图

数据化运营分析不止于“分析”,数据可视化也是其中一个重要的环节。可视化图形是每份报告的必备元素,这些图形包含不同的图形类型。
这里我们主要讨论下python中使用matplotlib画条形图的类型。

一、条形图的基本元素

垂直条形图:

matplotlib.pyplot.bar(x,height,width = 0.8,bottom = None,*,align =‘center’,data = None,** kwargs )

水平条形图:

matplotlib.pyplot.barh(y,width,height = 0.8,left = None,*,align =‘center’,** kwargs )

主要参数:

参数名称含义备注
xfloat或者array-like条形图中x的坐标。
heightfloat或者array-like条形图的高度
widthfloat或array-like条形图的宽度
bottomfloat或array-like条形图基座y坐标,默认0
align{‘center’, ‘edge’},默认值:‘center’条形图于x坐标的对齐:,center:实际x位置居中。edge:使条形图的左边缘与x位置对齐。
color颜色或颜色列表条形图的颜色
edgecolor颜色或颜色列表条形图的边缘的颜色
linewidthfloat or array-like边缘的的宽度,0则是不要绘制边缘
tick_labelstr或str列表,可选条形的刻度标签,默认值无
xerr,yerrfloat或shape(N,)或shape(2,N)的数组,如果不是None,则在条形图中添加水平或垂直的错误栏标量:所有条的对称+/-值shape(N,):每个条的对称+/-值。shape(2,N):每个条形的-和+值分开。第一行包含较低的错误第二行包含较高的错误。无:无错误栏。(默认
ecolor颜色或颜色列表,默认黑色误差线的线条颜色
capsizefloat, default: rcParams[“errorbar.capsize”] (default: 0.0)误差线的长度以磅为单位。
error_kwdict,可选将kwargs的字典传递给该errorbar 方法。价值观易彩或翻船这里定义的优先级高于独立kwargs。
logbool,默认值:False如果为True,则将y轴设置为对数刻度

其他**kwargs的Rectangle属性请参考官网

二、条形图的常见实例
看完上面的参数是不是感觉很简单。那么,我们看着实际例子来看下吧。
1、常规的条形图

import matplotlib
import matplotlib.pyplot as plt
import numpy as np


labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the label locations
width = 0.35  # 条形的宽

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men',edgecolor='grey',linewidth='1') #edgecolor条形图的边缘的颜色,linewidth边缘的宽度
rects2 = ax.bar(x + width/2, women_means, width, label='Women',edgecolor='grey',linewidth='1')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylim(0,40)
ax.legend()


def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)

fig.tight_layout()

plt.show()

在这里插入图片描述
2、对条形图的修正,不显示坐标轴

import matplotlib
import matplotlib.pyplot as plt
import numpy as np


labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the label locations
width = 0.35  # 条形的宽

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men',edgecolor='grey',linewidth='1') #edgecolor条形图的边缘的颜色,linewidth边缘的宽度
rects2 = ax.bar(x + width/2, women_means, width, label='Women',edgecolor='grey',linewidth='1')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_ylim(0,50)
ax.legend(bbox_to_anchor=(0.6,0.99),ncol=2,edgecolor='white') #调整图例
ax.spines['right'].set_visible(False) #右边的边框设置不可见
ax.spines['top'].set_visible(False)#上边的边框设置不可见
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.grid(axis='y')  #设置网格,axis参数axis值可以使x,y,both

# ax.set_yticks(())  #y轴坐标刻度不显示

def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)

fig.tight_layout()

plt.show()


在这里插入图片描述
到了这一步差不多包含我们常见的各种需求了,更多的操作可以查看官网。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值