Python画环形图
时间: 2024-09-26 11:17:51 浏览: 50
在Python中,你可以使用matplotlib库中的`pie()`函数来创建环形图,也被称为饼图。环形图用于显示各部分占总体的比例,并通过颜色和标签清晰地展示出来。以下是一个简单的例子:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['部分A', '部分B', '部分C', '部分D']
sizes = [40, 30, 25, 5] # 各部分所占百分比,总和应为100%
# 创建环形图
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140, pctdistance=0.85) # 自动添加百分比标签
# 添加背景圆环
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
# 设置图形标题和标签
plt.title('环形图示例')
plt.axis('equal') # 确保饼图是正圆形的,而不是椭圆形
plt.show()
相关问题
python画环形图_用Python把图做的好看点:用Matplotlib画个环形图
好的,以下是用 Python 的 Matplotlib 库画环形图的示例代码:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
# 颜色
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
# 环形图
fig1, ax1 = plt.subplots()
# 内环
ax1.pie([100], radius=0.7, colors=['w'])
# 外环
ax1.pie(sizes,
labels=labels,
colors=colors,
autopct='%1.1f%%',
startangle=90,
pctdistance=0.85,
labeldistance=1.1)
# 标题
ax1.set_title("环形图示例")
# 显示
plt.show()
```
运行以上代码,即可得到一个简单的环形图。
解释:
1. `labels` 和 `sizes` 分别为环形图的标签和大小。
2. `colors` 为环形图各部分的颜色。
3. `fig1, ax1 = plt.subplots()` 创建一个子图。
4. `ax1.pie([100], radius=0.7, colors=['w'])` 画内环。`[100]` 表示内环大小为 100,`radius=0.7` 表示内环半径为外环半径的 0.7,`colors=['w']` 表示内环颜色为白色。
5. `ax1.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90, pctdistance=0.85, labeldistance=1.1)` 画外环。`sizes` 为各部分的大小,`labels` 为各部分的标签,`colors` 为各部分的颜色。`autopct='%1.1f%%'` 表示显示各部分的百分比。`startangle=90` 表示从 90 度开始画图。`pctdistance=0.85` 表示百分比标签与圆心的距离,`labeldistance=1.1` 表示标签与圆心的距离。
6. `ax1.set_title("环形图示例")` 设置环形图标题。
7. `plt.show()` 显示图形。
python画环形桑基图
### 如何使用 Python 绘制环形桑基图
为了实现环形桑基图,可以利用 `plotly` 这一强大的可视化库。虽然标准的桑基图已经能够很好地表示流量关系,但是通过调整布局参数可以让图形呈现更接近于环形的效果。
下面是一个创建环形桑基图的具体实例:
```python
import plotly.graph_objects as go
# 定义节点和连接的数据结构
label = ["A", "B", "C", "D"]
source = [0, 1, 0, 2] # 节点索引列表,对应起始位置
target = [2, 3, 3, 3] # 节点索引列表,对应结束位置
value = [8, 4, 2, 8]
# 创建桑基图对象并配置属性
fig = go.Figure(data=[go.Sankey(
node=dict(
pad=15,
thickness=20,
line=dict(color="black", width=0.5),
label=label,
color="blue"
),
link=dict(
source=source,
target=target,
value=value
))])
# 更新布局使图表更加美观
fig.update_layout(title_text="Basic Sankey Diagram",
font_size=10)
# 显示图像前进一步定制其外观以形成闭环效果
# 可以尝试修改node的位置来模拟圆形排列
fig.update_traces(arrangement='snap')
# 展示最终结果
fig.show()
```
此段代码展示了如何构建基本的桑基图,并且可以通过调整节点(`node`)中的`pad`, `thickness`等参数以及链接(`link`)的相关设置来自定义显示风格[^2]。对于想要达到环形视觉效果的情况,则可能需要额外探索有关节点定位选项或是借助其他第三方工具辅助完成设计。
阅读全文
相关推荐

















