python数据可视化之条形图画法

Habiba ·
更新时间:2024-09-20
· 445 次阅读

什么是条形图?

条形图(bar chart)是用宽度相同的条形的高度或长短来表示数据多少的图形。条形图可以横置或纵置,纵置时也称为柱形图(column chart)。此外,条形图有简单条形图、复式条形图等形式。

简单来说,条形图的宽度一般是相同的,条形的高度或长短表示数据的多少,这也就是条形图和直方图的本质区别。

第一种画法

import numpy as np from pandas import DataFrame # 由于我们的x轴上刻度值是中文 需要使用这个包 进行中文的显示 from matplotlib.pyplot import rcParams # 显示中文  kaiti 表示 楷体 rcParams['font.sans-serif'] = 'kaiti' # 条形图(纵向) df = DataFrame(data=np.random.randint(50,100,size=(3,3)),                index=['张三','李四','王五'],                columns=['Python','En','Math']               ) df.plot(kind='bar',fontsize=20) # 运行结果如下图:

第二种画法

import numpy as np import matplotlib.pyplot as plt %matplotlib inline x = ['张三','李四','王五'] height = np.random.randint(80,100,size=3) plt.bar(x,height,width=0.2) height = np.random.randint(50,80,size=3) plt.bar(x,height,width=0.2) height = np.random.randint(10,80,size=3) plt.bar(x,height,width=0.2) # 设置图例  ncol 表示一行显示3个图例  loc 设置图例的位置 plt.legend(['数学成绩','Python成绩','英语成绩'],ncol=3,loc=(0,1)) # 运行结果如下:

第三种画法

使用pyecharts,pyecharts 是一个用于生成 Echarts 图表的类库。Echarts 是百度开源的一个数据可视化 JS 库。用 Echarts 生成的图可视化效果非常棒,为了与 Python 进行对接,方便在 Python 中直接使用数据生成图,简单便捷,可视化效果很棒,让我们来一起看看吧~。

import numpy as np from pyecharts.charts import Bar from pyecharts import options as opts # V1 版本开始支持链式调用 bar = (     Bar()     .add_xaxis(['张三','李四','王五'])     # 这里需要注意 y轴上传递的只能是列表 不能是数组,如果是数组 数据无法显示     .add_yaxis("python成绩",np.random.randint(40,100,size=3).tolist())       .add_yaxis("数学成绩",np.random.randint(40,100,size=3).tolist())     .add_yaxis("英语成绩",np.random.randint(40,100,size=3).tolist())     .set_global_opts(title_opts=opts.TitleOpts(title="某大学大三学生成绩条形图",subtitle='K班级'))       ) # 如果不习惯链式调用的可以使用常规操作 ''' bar = Bar() bar.add_xaxis(['张三','李四','王五']) bar.add_yaxis("python成绩",np.random.randint(40,100,size=3).tolist())  bar.add_yaxis("数学成绩",np.random.randint(40,100,size=3).tolist())  bar.add_yaxis("英语成绩",np.random.randint(40,100,size=3).tolist()) bar.set_global_opts(title_opts=opts.TitleOpts(title="某大学大三学生成绩条形图",subtitle='K班级')) ''' # 在 jupyter notebook上输出 bar.render_notebook() # 也可以渲染到本地html文件 # bar.render('./成绩.html') # 运行结果如下:



可视化 条形图 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号