【Python教程】绘制漂亮的柱状图

风杰同学_9658

风杰同学_9658

2017-02-07

4796人浏览

原创

matplotlib是基于python语言的开源项目,其旨在为python提供一个数据绘图包,本文简单介绍如何使用该程序包绘制漂亮的柱状图。

导入命令

1)设置工作环境%cd "F:\Dropbox\python"2)导入程序包import matplotlib.pyplot as plt
import numpy as np
from matplotlib.image import BboxImage
from matplotlib._png import read_png
import matplotlib.colors
from matplotlib.cbook import get_sample_data
import pandas as pd3)读取数据data=pd.read_csv("CAR.csv")4)定义并绘制图像
class RibbonBox(object):original_image = read_png(get_sample_data("Minduka_Present_Blue_Pack.png",asfileobj=False))cut_location = 70
b_and_h = original_image[:,:,2]
color = original_image[:,:,2] - original_image[:,:,0]
alpha = original_image[:,:,3]
nx = original_image.shape[1]def __init__(self, color):
rgb = matplotlib.colors.colorConverter.to_rgb(color)im = np.empty(self.original_image.shape,
self.original_image.dtype)im[:,:,:3] = self.b_and_h[:,:,np.newaxis]
im[:,:,:3] -= self.color[:,:,np.newaxis]*(1.-np.array(rgb))
im[:,:,3] = self.alphaself.im = imdef get_stretched_image(self, stretch_factor):
stretch_factor = max(stretch_factor, 1)
ny, nx, nch = self.im.shape
ny2 = int(ny*stretch_factor)stretched_image = np.empty((ny2, nx, nch),
self.im.dtype)
cut = self.im[self.cut_location,:,:]
stretched_image[:,:,:] = cut
stretched_image[:self.cut_location,:,:] = 
self.im[:self.cut_location,:,:]
stretched_image[-(ny-self.cut_location):,:,:] = 
self.im[-(ny-self.cut_location):,:,:]self._cached_im = stretched_image
return stretched_image
class RibbonBoxImage(BboxImage):
zorder = 1def __init__(self, bbox, color,
cmap = None,
norm = None,
interpolation=None,
origin=None,
filternorm=1,
filterrad=4.0,
resample = False,
**kwargs
):BboxImage.__init__(self, bbox,
cmap = cmap,
norm = norm,
interpolation=interpolation,
origin=origin,
filternorm=filternorm,
filterrad=filterrad,
resample = resample,
**kwargs
)self._ribbonbox = RibbonBox(color)
self._cached_ny = Nonedef draw(self, renderer, *args, **kwargs):bbox = self.get_window_extent(renderer)
stretch_factor = bbox.height / bbox.widthny = int(stretch_factor*self._ribbonbox.nx)
if self._cached_ny != ny:
arr = self._ribbonbox.get_stretched_image(stretch_factor)
self.set_array(arr)
self._cached_ny = nyBboxImage.draw(self, renderer, *args, **kwargs)if 1:
from matplotlib.transforms import Bbox, TransformedBbox
from matplotlib.ticker import ScalarFormatterfig, ax = plt.subplots()years = np.arange(2001,2008)
box_colors = [(0.8, 0.2, 0.2),
(0.2, 0.8, 0.2),
(0.2, 0.2, 0.8),
(0.7, 0.5, 0.8),
(0.3, 0.8, 0.7),
(0.4, 0.6, 0.3),
(0.5, 0.5, 0.1),
]
heights = data['price']fmt = ScalarFormatter(useOffset=False)
ax.xaxis.set_major_formatter(fmt)for year, h, bc in zip(years, heights, box_colors):
bbox0 = Bbox.from_extents(year-0.4, 0., year+0.4, h)
bbox = TransformedBbox(bbox0, ax.transData)
rb_patch = RibbonBoxImage(bbox, bc, interpolation="bicubic")ax.add_artist(rb_patch)
ax.annotate(h,
(year, h), va="bottom", ha="center")
ax.set_title('The Price of Car')patch_gradient = BboxImage(ax.bbox,
interpolation="bicubic",
zorder=0.1,
)
gradient = np.zeros((2, 2, 4), dtype=np.float)
gradient[:,:,:3] = [1, 1, 0.]
gradient[:,:,3] = [[0.1, 0.3],[0.3, 0.5]]
patch_gradient.set_array(gradient)
ax.add_artist(patch_gradient)ax.set_xlim(years[0]-0.5, years[-1]+0.5)
ax.set_ylim(0, 15000)5)保存图像fig.savefig('The Price of Car.png')
plt.show()

输出图像如下

361SCAN security check your skill python scripts
361SCAN security check your skill python scripts

扫描并分析已安装技能,用于查看指定技能目录的名称、描述和详情,或列出所有已安装的技能。

下载

979.jpg

以上就是【Python教程】绘制漂亮的柱状图的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!

相关文章

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

python

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Gradle插件开发入门教程
Gradle插件开发入门教程

本专题介绍Gradle插件开发的基本流程,涵盖插件类编写、自定义任务注册、扩展参数设计和插件应用方法,帮助你理解插件如何组织构建逻辑,减少多个项目之间的重复配置。

2026.10.22

20

11

Gradle Wrapper配置教程
Gradle Wrapper配置教程

本专题介绍Gradle Wrapper的基本作用,涵盖文件组成、生成方法、版本配置和任务调用,帮助你理解项目如何使用指定的Gradle版本,减少不同开发环境带来的构建差异。

2026.10.22

20

10

Golangci-lint检查器使用教程
Golangci-lint检查器使用教程

本专题整理Golangci-lint常用Linters的用途与配置方法,覆盖错误处理、无效代码、安全、复杂度、命名和依赖检查,帮助项目合理选规则。

2026.10.22

20

15

Gradle怎么构建Java项目
Gradle怎么构建Java项目

本专题介绍Gradle Java项目构建方法,涵盖Java插件配置、依赖声明、源码编译、测试执行和打包检查,帮助你理解各阶段的任务关系,逐步完成项目构建。

2026.10.22

0

10

PHP时间戳漏洞修复教程
PHP时间戳漏洞修复教程

本专题汇总PHP常见时间戳漏洞,包括2038年溢出、时区漂移、时间戳伪造、重放攻击、时间盲注与日志审计失效等,并给出升级64位环境、使用 DateTimeImmutable、统一UTC、严格超时校验、预处理绑定、hash_equals 比对等修复方案,帮助开发者快速排查和加固时间相关代码。

2026.10.22

20

25

Golangci-lint配置文件与规则设置
Golangci-lint配置文件与规则设置

本专题聚焦Golangci-lint YAML配置文件,讲清运行参数、规则启停、目录排除、问题过滤及严重级别设置,便于团队统一检查标准。

2026.10.22

20

15

Golangci-lint安装与入门教程
Golangci-lint安装与入门教程

本专题讲解Golangci-lint的安装、初始化、基础命令和首次代码检查,覆盖本地环境、Docker及多平台用法,帮助Go开发者快速上手。

2026.10.22

20

15

PHP2Shell高危漏洞修复教程
PHP2Shell高危漏洞修复教程

PHP2Shell漏洞是什么,哪些PHP版本和运行环境会受到影响,服务器应该如何检测与修复?本专题提供版本自查脚本、Linux与Docker升级命令、PHP-FPM和Apache排查步骤,以及修复验证、临时缓解和应急响应方案。

2026.10.22

100

12

剧云人物设定与关系管理教程
剧云人物设定与关系管理教程

本专题介绍剧云人物设定与关系管理,讲解角色小传、性格职业、人物目标、背景资料和关系网络的创建及维护方法。

2026.10.22

20

16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Uvicorn官方安装与入门手册
Uvicorn官方安装与入门手册

共0课时 | 0人学习

Python uv官方项目管理指南
Python uv官方项目管理指南

共0课时 | 0人学习

Python uv官方安装与入门文档
Python uv官方安装与入门文档

共0课时 | 0人学习