sklearn 中matplotlib编制图表

代码

python 复制代码
# 导入pandas库,并为其设置别名pd
import pandas as pd
import matplotlib.pyplot as plt

# 使用pandas的read_csv函数读取名为'iris.csv'的文件,将数据存储在iris_data变量中
iris_data = pd.read_csv('data/iris.txt',sep='\t')

# 使用groupby方法按照"species"列(即花的种类)对数据进行分组
# 分组后的数据存储在grouped_data变量中
grouped_data = iris_data.groupby("species")

# 对每个分组计算平均值,结果存储在group_mean变量中
group_mean = grouped_data.mean()

# 使用plot方法绘制条形图,其中kind="bar"表示绘制条形图
# rot=15表示x轴的标签旋转15度以便更好地显示
# figsize=(8, 5)表示图形的大小为宽8英寸、高5英寸
#group_mean.plot(kind="bar", rot=15, figsize=(8, 5))
barstyle=['line','hist','box','kde','area','bar','scatter']
for item in barstyle:
    group_mean.plot(kind=item, rot=15, figsize=(8, 5))
    # 使用plt.legend方法添加图例,其中loc="upper center"表示图例的位置在图形的上方中央
    # bbox_to_anchor=(0.5,1.2)表示图例的具体位置相对于图形中心的偏移量
    # ncol=2表示图例分为两列显示
    plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.2), ncol=2)

    # 使用plt.show()方法显示图形
    plt.show()

kind 参数在 pandas 的 plot 方法中确实有多种可选值,它决定了图形的类型。除了 "bar"(条形图)之外,以下是一些常用的 kind 参数值及其对应的图形类型:

"line": 折线图

"barh": 水平条形图

"hist": 直方图

"box": 箱线图

"kde": Kernel Density Estimation 图(核密度估计图)

"area": 面积图

"pie": 饼图

"scatter": 散点图

例如,如果你想绘制一个折线图而不是条形图,你可以将 kind 参数改为 "line":

图形






相关推荐
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1233 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero073 天前
Jev 与 Laya
python·语言模型