Python可视化数据分析-饼状图

一、前言

饼状图(Pie Chart)是一种常用的数据可视化图表,用于展示数据中各部分的占比关系。Python 中有多种库可以用于绘制饼状图,比较常用的包括 matplotlibpyecharts plotly 等。

二、使用 matplotlib 绘制饼状图
import matplotlib.pyplot as plt

# 数据
labels = ['Apples', 'Oranges', 'Bananas', 'Grapes']
sizes = [30, 25, 20, 25]  # 每部分的占比
colors = ['gold', 'orange', 'lightgreen', 'lightcoral']  # 颜色
explode = (0.1, 0, 0, 0)  # 突出显示第一部分

# 绘制饼状图
plt.figure(figsize=(8, 6))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=140)
plt.title('Fruit Distribution')  # 图表标题
plt.axis('equal')  # 使饼状图长宽相等
plt.show()

说明:

  1)labels 是各部分的标签。

  2)sizes 是各部分的大小(占比)。

  3)colors 是各部分的颜色。

  4)explode 是用于突出显示某部分的偏移量,0 表示不突出                                                       

效果图 :

            

三、使用 plotly 绘制饼状图
import plotly.express as px

# 数据
labels = ['Apples', 'Oranges', 'Bananas', 'Grapes']
sizes = [30, 25, 20, 25]  # 每部分的占比

# 创建图表
fig = px.pie(values=sizes, names=labels, title='Fruit Distribution')

# 显示图表
fig.show()

说明:

 1)labels 是各部分的标签。

 2)sizes 是各部分的大小(占比)。

    3) 使用 plotly.expresspx.pie 函数创建饼状图。

 4)fig.show() 方法用于显示图表。

效果图:

四、使用 pyecharts 生成饼状图
from pyecharts import options as opts
from pyecharts.charts import Pie

# 数据
labels = ['Apples', 'Oranges', 'Bananas', 'Grapes']
sizes = [30, 25, 20, 25]  # 每部分的占比

# 创建饼状图对象
pie_chart = Pie()

# 添加数据和配置
pie_chart.add("", [list(z) for z in zip(labels, sizes)], radius=["30%", "75%"])

# 设置全局配置
pie_chart.set_global_opts(title_opts=opts.TitleOpts(title="Fruit Distribution"))

# 显示图表(生成 HTML 文件)
pie_chart.render("pie_chart.html")

上述代码中使用了 pyecharts 库的 Pie 类来创建饼状图。我们可以通过添加数据和配置来自定义饼状图的样式和布局。最后,调用 render 方法将图表生成为 HTML 文件并显示出来。

效果图:

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-21 09:00:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-21 09:00:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-21 09:00:05       82 阅读
  4. Python语言-面向对象

    2024-04-21 09:00:05       91 阅读

热门阅读

  1. Stylus 入门使用方法

    2024-04-21 09:00:05       31 阅读
  2. Stylus入门使用方法

    2024-04-21 09:00:05       44 阅读
  3. stylus入门使用方法

    2024-04-21 09:00:05       40 阅读
  4. leetcode748-Shortest Completing Word

    2024-04-21 09:00:05       31 阅读
  5. 游程编码(Run-Length Encoding, RLE)的python实现

    2024-04-21 09:00:05       24 阅读
  6. 吉林教育报社投稿信箱投稿邮箱

    2024-04-21 09:00:05       28 阅读
  7. 面试 Python 基础八股文十问十答第二期

    2024-04-21 09:00:05       40 阅读
  8. 前端开发中可以使用的 ChatGPT Prompts

    2024-04-21 09:00:05       37 阅读
  9. nodejs(项目架构MVC,IOC,DI)

    2024-04-21 09:00:05       37 阅读