matplotlib 图表生成
条形颜色演示
import matplotlib.pyplot as plt
'''
将plt.subplots()函数的返回值赋值给fig和ax俩个变量
plt.subplots()是一个函数,返回一个包含figure和axes对象的元组
'''
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', 'pink', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:pink', 'tab:orange']
'''
ax.bar(x,height,width,bottom,align)
x:一个标量序列,代表柱状图的x坐标,默认x取值是每个柱状图所在的中点位置,或者也可以是柱状图左侧边缘位置
hegiht:一个标量或者是标量序列,代表柱状图的高度
width:可选参数,标量或类数组,柱状图的默认宽度值为0.8
bottom可选参数,柱状图的y坐标默认为None
algin有俩个可选项{center,edge},默认为center,该参数决定x值位于柱状图的位置
'''
# ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
#添加y轴标题
ax.set_ylabel('fruit supply')
#图表标题
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
# plt.savefig('./q1.jpg')`

条形标签演示
import matplotlib.pyplot as plt
import numpy as np
species = ('Adelie', 'Chinstrap', 'Gentoo')
sex_counts = {
'Male': np.array([73, 34, 61]),
'Female': np.array([73, 34, 58]),
}
width = 0.6 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots()
'''
np.zeros函数的作用
返回来一个给定形状和类型的用0填充的数组
zeros(shape,dtype=float,order='C')
shape:形状
dtype:数据类型,可选参数
order:可选参数,c 行优先,f列优先
'''
bottom = np.zeros(3)
# print(bottom)
for sex, sex_count in sex_counts.items():
p = ax.bar(species, sex_count, width, label=sex, bottom=bottom)
bottom += sex_count
ax.bar_label(p, label_type='center')
ax.set_title('Number of penguins by sex')
#ax.legend()
ax.legend()
plt.show()

堆积条形图
import matplotlib.pyplot as plt
import numpy as np
# data from https://allisonhorst.github.io/palmerpenguins/
species = (
"Adelie\n $\\mu=$3700.66g",
"Chinstrap\n $\\mu=$3733.09g",
"Gentoo\n $\\mu=5076.02g$",
)
weight_counts = {
"Below": np.array([70, 31, 58]),
"Above": np.array([82, 37, 66]),
}
width = 0.5
fig, ax = plt.subplots()
bottom = np.zeros(3)
for boolean, weight_count in weight_counts.items():
p = ax.bar(species, weight_count, width, label=boolean, bottom=bottom)
bottom += weight_count
ax.set_title("Number of penguins with above average body mass")
ax.legend(loc="upper right")
plt.show()

带标签的分组条形图
# data from https://allisonhorst.github.io/palmerpenguins/
import matplotlib.pyplot as plt
import numpy as np
species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {
'Bill Depth': (18.35, 18.43, 14.98),
'Bill Length': (38.79, 48.83, 47.50),
'Flipper Length': (189.95, 195.82, 217.19),
}
x = np.arange(len(species)) # the label locations
width = 0.25 # the width of the bars
multiplier = 0
fig, ax = plt.subplots(layout='constrained')
for attribute, measurement in penguin_means.items():
offset = width * multiplier
rects = ax.bar(x + offset, measurement, width, label=attribute)
ax.bar_label(rects, padding=3)
multiplier += 1
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)
plt.show()

水平条形图
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
plt.show()

饼状图
import matplotlib.pyplot as plt
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels)

饼图和圆环图
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))
recipe = ["375 g flour",
"75 g sugar",
"250 g butter",
"300 g berries"]
data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1] for x in recipe]
def func(pct, allvals):
absolute = int(np.round(pct/100.*np.sum(allvals)))
return f"{pct:.1f}%\n({absolute:d} g)"
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
textprops=dict(color="w"))
ax.legend(wedges, ingredients,
title="Ingredients",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=8, weight="bold")
ax.set_title("Matplotlib bakery: A pie")
plt.show()

matplotlib 图表生成的更多相关文章
- 一行代码让matplotlib图表变高大上
1 简介 matplotlib作为Python生态中最流行的数据可视化框架,虽然功能非常强大,但默认样式比较简陋,想要制作具有简洁商务风格的图表往往需要编写众多的代码来调整各种参数. 而今天要为大家介 ...
- 2018.03.29 python-matplotlib 图表生成
'''Matplotlib -> 一个python版的matlab绘图接口,以2D为主,支持python,numpy,pandas基本数据结构,高效图标库''' import numpy as ...
- matplotlib图表介绍
Matplotlib 是一个python 的绘图库,主要用于生成2D图表. 常用到的是matplotlib中的pyplot,导入方式import matplotlib.pyplot as plt 一. ...
- [Python] Matplotlib 图表的绘制和美化技巧
目录 在一张画布中绘制多个图表 加图表元素 气泡图 组合图 直方图 雷达图 树状图 箱形图 玫瑰图 在一张画布中绘制多个图表 Matplotlib模块在绘制图表时,默认先建立一张画布,然后在画布中显示 ...
- Python tkinter库将matplotlib图表显示在GUI窗口上,并实时更新刷新数据
代码 1 ''' 2 使用matplotlib创建图表,并显示在tk窗口 3 ''' 4 import matplotlib.pyplot as plt 5 from matplotlib.pylab ...
- JFreeChart 图表生成实例(饼图、柱状图、折线图、时序图)
import java.awt.BasicStroke; import java.awt.Color; import java.io.FileOutputStream; import java.io. ...
- matplotlib图表组成元素
一.函数 1.plot() -- 展示变量的趋势与变化 用法: plt.plot(x,y,ls="-",lw=2,label="plot figure" ...
- Matplotlib 图表的样式参数
1. import numpy as np import pandas as pd import matplotlib.pyplot as plt % matplotlib inline # 导入相关 ...
- Matplotlib 图表的基本参数设置
1.图名,图例,轴标签,轴边界,轴刻度,轴刻度标签 # 图名,图例,轴标签,轴边界,轴刻度,轴刻度标签等 df = pd.DataFrame(np.random.rand(10,2),columns= ...
- python matplotlib 图表局部放大
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes ...
随机推荐
- 巅峰对决:英伟达 V100、A100/800、H100/800 GPU 对比
近期,不论是国外的 ChatGPT,还是国内诸多的大模型,让 AIGC 的市场一片爆火.而在 AIGC 的种种智能表现背后,均来自于堪称天文数字的算力支持.以 ChatGPT 为例,据微软高管透露,为 ...
- linux 使用crontab 创建定时任务
转载请注明出处: 在服务器中需要创建一个定时任务,每天执行去清理很早之前备份的文件,所以想到在linux上创建一个shell脚本,通过linux的 crontab 命令定时去执行该shell脚本,从而 ...
- 记录jdk17相对于jdk8增加的一下主要语法糖和新特性
jdk17 发布已经好久了,作为java的长期支持版本,引入了许多有趣且实用的新特性.这些特性不仅提高了开发效率,还增强了语言的表现力和安全性.并且是SpringBoot 3.0以后版本的硬性要求,之 ...
- PTA作业4、5、6及期中考试的总结
一.前言 本次博客是针对面向对象程序设计课程布置的PTA第4.5.6次作业以及期中考试的编程题而写的总结分析,重点分析了菜单计价系列题目.期中考试的编程题等具有一定难度和特色的问题. 二.PTA第四次 ...
- 从一个 Demo 说起 Dubbo3
简介 2017年的9月份,阿里宣布重启Dubbo的开发维护,并且后续又将Dubbo捐献给了Apache,经过多年的发展已经发布到3.X版本了,Dubbo重启维护之后是否有值得我们期待的功能呢,下面就来 ...
- 1. Shell 基本用法
重点: 条件测试. read. Shell 环境配置. case. for. find. xargs. gzip,bzip2,xz. tar. sed. 1)编程基础 Linus 说:Talk is ...
- 黑客玩具入门——2、Kali常用命令与简单工具
一.Linux常用命令 首先,我们启动kali系统,然后点击这里的命令行工具. 就可以使用下面学习的命令了,另外,如果你有过计算机基础,那么Mac的terminal和Git的gitbash,都是可以练 ...
- mac中删除本地maven库中下载失败的.lastUpdated文件
在 macOS 中,要删除本地 Maven 仓库中所有的 .lastUpdated 文件,您可以使用 find 命令结合 rm 命令来执行这个操作.这可以在终端(Terminal)中完成. 打开您的终 ...
- Go 泛型之类型参数
Go 泛型之类型参数 一.Go 的泛型与其他主流编程语言的泛型差异 Go泛型和其他支持泛型的主流编程语言之间的泛型设计与实现存在差异一样,Go 的泛型与其他主流编程语言的泛型也是不同的.我们先看一下 ...
- 华企盾DSC半透明无法打开加密文件常见处理方法
1.查看客户端日志进程是否显示legal:1 2.半透明只支持双击打开 3.半透明进程不能设置HOOK白名单 4.检查调用的进程是否都加了 5.半透明程序的运行方式不可以以管理员启动,去掉" ...